O.nunez O.nunez - 2 months ago 24
C Question

null compare in C language

i already have this code in C language, is a string of 15 data delimited by commas the code split the string by comma and store every data in a single variable called array[], the issue is that i have the last data comma if after the last comma there are no data then the variable x15 = 0, but if there are a value after the last , then convert that value to a int. i print the value of the array[15] to verify and this is null, so i out a condition for that but do not work, the program just break after compiling.

char buf[] ="¶bL0 L3,01,+08590323,-079343001,010215,00000000000000,-tN,000,012689997,001219456,000,7FF2,C07F,0,4,";

printf("\n \n string=[%s]\n\n", buf);
int i = 0;
int u;
char *p = strtok (buf, ",");
char *array[16];
char *y15;
while (p != NULL)
{
array[i++] = p;
p = strtok (NULL, ",");
}

for (i = 0; i <16; ++i){
if(array[15] == NULL){
wbt.x15=0;
}else{
wbt.x15=atoi(array[15]);
}

//printf("data: [%s]\n", array[i]);
}

Answer

You are using an uninitialized array element, which is cause for undefined behavior.

You have:

char *array[16];

The elements of the array are uninitialized. And then, you proceed to use:

  if(array[15] == NULL){
     wbt.x15=0;
  }else{
     wbt.x15=atoi(array[15]);
  }

It's not clear why you have that check for every iteration of the loop but that's another problem. The problem with the posted code is that array[15] is not initialized. Using that value is a problem.

Make sure you initialize array properly. Use:

char *array[16] = {0};

Also, I think your for loop needs to be something like:

for (i = 0; i <16; ++i)
{
   int x = 0;
   if(array[i] != NULL)
   {
      x = atoi(array[i]);
   }

   // Now use x.
}