sizeof char* array in C/C++

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

    It looks as though you have a pointer, not an array. Arrays are converted to pointers when the program requires it, so you'd get:

    size_t size(char * p) { // p is a pointer
        return sizeof(p) / sizeof(*p); // size of pointer
    }
    
    size_t size(char p[]) { // p is also a pointer        
        return sizeof(p) / sizeof(*p); // size of pointer
    }
    

    although, since sizeof (char) == 1, the division is redundant here; if the pointer were to a larger type, then you'd get a differently unexpected result.

    In C++ (but obviously not C), you can deduce the size of an array as a template parameter:

    template 
    size_t size(T (&)[N]) {
        return N;  // size of array
    }
    

    or you can use classes such as std::vector and std::string to keep track of the size.

    In C, you can use strlen to find the length of a zero-terminated string, but in most cases you'll need to keep track of array sizes yourself.

提交回复
热议问题