How to know the size (in bytes) of a char array passed to a function?

女生的网名这么多〃 提交于 2019-12-20 05:36:48

问题


I am testing the sizeof operator. In two cases in my code, I get the size of the pointer (I think). In the other cases I get how many bytes the arrays occupy. How can I get the size of the array in bytes when I pass it to a function? Isn't the sizeof operator enough? Am I doing something wrong?

#include <stdio.h>

/*Testing the operator sizeof*/

void test (char arrayT[]);
void test2 (char *arrayU);

int main(int argc, char *argv[]){

    char array1[7];
    printf("array1 size is:%d\n", sizeof array1);
    /*array1 size is: 7*/

    char array2[] = { '1', '2', '3', '4', '5', '6', '7'};
    printf("array2 size is:%d\n", sizeof array2);
    /*array2 size is: 7*/

    char array3[] = "123456";
    printf("array3 size is:%d\n", sizeof array3);
    /*array3 size is: 7*/

    unsigned char array4[] = "123456";
    printf("array4 size is:%d\n", sizeof array4);
    /*array4 size is: 7*/

    char arrayX[] = "123456";
    test(arrayX);
    /*arrayT size is: 4*/

    char arrayY[] = "123456";
    test2(&arrayY[0]);
    /*arrayU size is: 4*/

    return 0;
}

void test (char arrayT[]){
    printf("arrayT size is:%d\n", sizeof arrayT);
}

void test2 (char *arrayU){
    printf("arrayU size is:%d\n", sizeof arrayU);
}

回答1:


When an array is passed to a function, what's actually happening is that a pointer to the first element in the array is being passed. Put another way, the array decays into a pointer to the first element.

In these two declarations:

void test (char arrayT[]);
void test2 (char *arrayU);

arrayT and arrayU are of exactly the same type due to this decay, and sizeof will return the same value for both, i.e. the size of a char *.

Contrast the above with this:

char array1[] = "a string";
char *array2;

Where array1 is actually an array of size 9, while array2 is a pointer whose size (on your system) is 4.

Because of this, there is no way to know the length of an array passed to a function. You need to pass in the size as a separate parameter:

void test (char arrayT[], size_t len);


来源:https://stackoverflow.com/questions/33221983/how-to-know-the-size-in-bytes-of-a-char-array-passed-to-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!