问题描述
使用此代码:
#include <stdio.h>
void printSize(char *messages[]) {
printf("%d", sizeof(messages) / sizeof(char *));
}
int main(void) {
printf("Size when through passing direct to function: ");
printSize((char *[]){"Zero", "One", "Two", "Three"});
printf("\n");
printf("Size when calculating in main: %d\n", sizeof((char *[]){"Zero", "One", "Two", "Three"}) / sizeof(char *));
return 1;
}
我得到输出:
Size when through passing direct to function: 1
Size when calculating in main: 4
我知道无法在 char* 数组中获得正确数量的元素,但我很好奇为什么它们会给出不同的结果.
I understand there is no way to get the correct amount of elements in a char* array, but I am curious as to why they are giving different results.
推荐答案
当您使用数组作为函数的参数时,它会衰减"到指向数组第一个元素的指针.由于messages
是一个指向char
的指针数组,当数组被传递给函数时,它就变成了一个指向char 的指针的指针.即使您在参数列表中将其指定为数组,也会发生这种情况;这就是语言的工作方式.
When you use an array as a parameter to a function, it "decays" to a pointer to the first element of the array. Since messages
is an array of pointers to char
, when the array is passed to the function, it becomes a pointer to a pointer to a char. This happens even though you are specifying it as an array in your parameter list; that is just how the language works.
因此在void printSize()
中,当您使用sizeof(messages)
时,您将获得指针的大小.您将其除以另一个指针的大小sizeof (char*)
.在您的系统上,指针的大小在两种情况下都是 4 个字节,因此您得到的结果是 4/4,即 1.
So in void printSize()
, when you use sizeof(messages)
, you get the size of a pointer. You are dividing that by the size of another pointer sizeof (char*)
. On your system, the size of a pointer is 4 bytes in both cases, so the result you get is 4 / 4, i.e., 1.
在main()
中,char*
的数组被定义为一个数组.当 sizeof()
运算符应用于数组时,您将获得整个数组中所有字节的大小.这是什么数组?它是一个包含四个指向 char
的指针的数组.每个指针的大小为 4.因此数组的总大小为 4 * 4 = 16 字节.您将此 16 除以指向 char 的单个指针的大小,即 4.因此您得到的结果为 16/4,即 main()
中的答案为 4.
In main()
, however, your array of char*
is defined as, and treated as, an array. When the sizeof()
operator is applied to an array, you get the size of all the bytes in the entire array. What is this an array of? It's an array of four pointers to char
. Each pointer has the size 4. So the total size of the array is 4 * 4 = 16 bytes. You are dividing this 16 by the size of a single pointer to char, which is 4. So you are getting the result 16 / 4, i.e. 4 as the answer in main()
.
这篇关于来自函数的字符指针数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!