sizeof char* array in C/C++

后端 未结 6 700
旧巷少年郎
旧巷少年郎 2021-02-14 07:57

There are plenty of similar inquires, but in my case I don\'t understand what isn\'t working:

int mysize = 0;
mysize = sizeof(samplestring) / sizeof(*samplestrin         


        
6条回答
  •  野的像风
    2021-02-14 08:39

    There are two ways of making a string constant, and your technique only works on the first one. The first one makes an array of characters which you can get the size of at compile time, and the other creates a pointer to an array of characters.

    char samplestring[] = "hello";
    char * samplestring = "hello";
    

    Trying to take the size of the second case the way you're doing it just gives you the size of a pointer. On a 32-bit build the size of a pointer is 4 characters, i.e. a pointer takes the same amount of memory as 4 characters.

    The following will always give the correct length for a properly null-terminated string, but it's slower.

    mysize = strlen(samplestring);
    

提交回复
热议问题