从功能字符指针数组的大小

编程入门 行业动态 更新时间:2024-10-25 20:22:29
本文介绍了从功能字符指针数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用这个code:

#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.

推荐答案

当您使用数组作为参数传递给一个函数,它衰变的指针数组的第一个元素。由于的消息为指针,以字符一个数组,当数组传递给函数,它成为一个指针一个指针为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.

因此​​,在无效printSize(),当你使用的sizeof(消息),你得到的大小指针。您除以另一个指针的大小的sizeof(字符*)。在您的系统中,指针的大小是在两种情况下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()运算符应用于一个数组,你会得到整个阵列中的所有字节大小。这是什么的数组?它的四个指针数组字符。每个指针有大小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().

更多推荐

从功能字符指针数组的大小

本文发布于:2023-07-29 00:51:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235724.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   指针   字符   大小   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!