sizeof char* array in C/C++

后端 未结 6 728
旧巷少年郎
旧巷少年郎 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:25

    First of all, sizeof(samplestring[0]) is the same as sizeof(*samplestring), they're both returning the size of the first element of the samplestring array. And, assuming samplestring is an array of chars, sizeof(char) is defined to be 1.

    You haven't shown how samplestring is declared. It could be one of the following:

    char const *samplestring = "Hello, World!";
    

    or

    char *samplestring = malloc( ... );
    

    or

    char samplestring[10];
    

    In the first 2 cases the type of samplestring is char *, so sizeof(samplestring) returns sizeof(char *), which, on your platform is 4.

    In the third case, the type of samplestring is char[10] (array of 10 chars), but if you call a function that takes a char * as its parameter, the char array will decay to a pointer pointing to the first element of the array. In this case, trying to print sizeof within the function will still result in the size of a pointer being printed.

    If you want the size of the original array to be printed from within the function, then the function parameter needs to be a pointer to the original array type (and the type includes size of the original array).

    #include 
    
    void foo( char (*arr)[42] )
    {
      printf( "%u", (unsigned)sizeof(*arr) );
    }
    
    int main()
    {
      char arr[42];
      foo( &arr );
    
      return 0;
    }  
    

    Output:

    42
    

    This fixes the size of the array that can be passed to the function and is not desirable in a lot of cases. The only other solution is to keep track of the array yourself (or use strlen if you have a NULL terminated string).

提交回复
热议问题