简体   繁体   中英

Why does realloc not update the size of my array?

I am trying to read in user input then parse it to tokens using strtok(). Here is my code:

int main(){
char argv[200];
char** tokenList = NULL;

printf("shell>>");
scanf("%[^\n]%*c", argv);
int len = 0;
char* line = strtok(argv, " ");
while (line != NULL) {
   printf("%s\n", line);
   printf("%lu\n", sizeof(tokenList) + (sizeof(char*) * (len+1)));
   tokenList = realloc(tokenList, sizeof(tokenList) + (sizeof(char*) * (len+1)));
   printf("%lu\n", sizeof(tokenList));
   char* p = malloc(sizeof(char) * (sizeof(line) + 1));
   p=line;
   tokenList[len] = p;
   len++;
   line = strtok(NULL, " ");
  }

The three print statements are for my debugging purposes and I cannot figure out what is going on. When I run the shell and enter "abc" my output is the following:

a
16
8
b
24
8
c
32
8

Why is the size of my array tokenList not getting updated by the realloc call?

You are using sizeof operator on a pointer. This yields the size in bytes of the pointer , not of the length of data pointed to. It's easy to imagine why, since tokenList is just a variable that stores an address, you obtain the size of the variable, not of what the variable points to.

In C, arrays allocated on heap doesn't know their size, the developer must take care of knowing it and storing/updating it when necessary somewhere.

The only case in which you are allowed to use directly sizeof is when an array is declared with static or local storage (and not on heap). In this circumstance sizeof return the total length in bytes of the array, so that you can do sizeof(array) / sizeof(array[0]) to obtain the element count.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM