0

I am trying to zero out an array element and check its status so it won't be used again, however, it seems doesn't work.

int main(int argc, char const *argv[]){
  char pid[10][20] = {"abc", "dec", "dsz", "dfas"};
  memset(pid[1],0,sizeof(pid[1]));
  for (int i=0; i<4;i++){
    printf("element %d: %s\n", i, pid[i]);
  }
  if (pid[1] == 0){
    printf("It's empty\n");
  } else{
    printf("Not empty\n");
  }
  return 0;
}

I also used memset(pid[1],NULL,sizeof(pid[1])) and check if pid[1] == NULL but it gives me the same result. Any help would be so much appreciated !

Chocode
  • 147
  • 9
  • Why would a pointer to an object with automatic storage duration *ever* be a nullpointer? – EOF Mar 29 '22 at 19:16
  • If you can image `pid[10][20]` as matrix of `10x20` characters, that `memset()` only made 2 row empty(0). So, `pid[1]` becomes an empty string. base address is still the same. In fact you can't assign `NULL` to array type. i.e. `pid[1] = NULL` is wrong. – जलजनक Mar 29 '22 at 19:44

1 Answers1

1

pid[1] is an element of pid. pid is a 10-element array of char[20], so pid[1] is a 20-element array of char.

pid[1] is an array, so it is converted to a pointer to its first element when it is used in expressions like pid[1] == 0. The conversion result won't be NULL because it should be a valid array.

What you want to do looks like checking if the string is an empty string like strcmp(pid[1], "") == 0.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • The following link may provide a further explanation: [What is array to pointer decay?](https://stackoverflow.com/q/1461432/12149471) However, that link may also be confusing, as it also deals with C++ and is not limited to C. – Andreas Wenzel Mar 29 '22 at 19:21