函数中字符指针数组的大小 [英] Size of char pointer array from function

查看:17
本文介绍了函数中字符指针数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此代码:

#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("
");

    printf("Size when calculating in main: %d
", 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,即 4 作为 main() 中的答案.

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().

这篇关于函数中字符指针数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆