Home > Mobile >  Can't initialize a NULL char array?
Can't initialize a NULL char array?

Time:04-08

I have to inizialize a char array [DIM_MAX] to a null value in order to pass it to another function. Before passing it to this function, I am trying to print it as a local variable in order to understand if it assumes a value of zero, but unfortunately this does not happen.

I did:

 static char bufferW[DIM_WRITE];

Then I wanted to inizialize this buffer to zero. Is correct to do this?

*bufferW="NULL";

I have to pass it to the function

write(0x02900800, bufferW, DIM_WRITE);

but bufferW isn't passed as a NULL char, it is the last value assumed. Where am I doing wrong? I tried:

bufferW==NULL;

is the way? I am sorry for the basic question. Any help will be appreciated

kind regards

CodePudding user response:

bufferW is an array, which takes up DIM_WRITE bytes.

If you're trying to set every byte in the array to 0, the function you want to call is

memset(bufferW, 0, DIM_WRITE); //Make sure to #include <string.h>

If you don't have access to the functions prototyped in string.h, you can also overwrite the buffer with a simple loop such as

for(int i = 0; i < DIM_WRITE;   i)
  bufferW[i] = 0;

You can do this at any time in your program to overwrite the values in bufferW, but if you haven't written anything to the buffer yet, the static scope specifier in the declaration ensures it will be initialized to zero at the start of your program.

To write the string "NULL" in the buffer you can

strcpy(bufferW,"NULL"); //Make sure to #include <string.h>

Or manually write each character in the buffer

bufferW[0] = 'N';
bufferW[1] = 'U';
bufferW[2] = 'L';
bufferW[3] = 'L';
bufferW[4] = '\0'; //Null terminator

But for these to work DIM_WRITE must be at least 5.

  • Related