如何获得数组在C的长度?是" sizeof的"是溶液中的一个? [英] How to get the length of array in C? is "sizeof" is one of the solution?

查看:129
本文介绍了如何获得数组在C的长度?是" sizeof的"是溶液中的一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/1975128/sizeof-an-array-in-the-c-programming-language\">Sizeof在C编程语言中数组?结果
  <一href=\"http://stackoverflow.com/questions/2950332/why-does-a-c-array-have-a-wrong-sizeof-value-when-its-passed-to-a-function\">Why当它传递给一个函数做了C-阵列有一个错误的sizeof()值?

请参阅下面的code和建议我那是什么的区别的sizeof 关键字时,我用这样的:

See the below code and suggest me that what is the difference of "sizeof" keyword when I used like this:

#include<stdio.h>
#include<conio.h>
void show(int ar[]);
void main()
{
    int arr[]={1,2,3,4,5};
    clrscr();
    printf("Length: %d\n",sizeof(arr));
    printf("Length: %d\n",sizeof(arr)/sizeof(int));
    show(arr);
    getch();
}
void show(int ar[])
{
   printf("Length: %d", sizeof(ar));
   printf("Length: %d", sizeof(ar)/sizeof(int));
}

但输出是这样的:

But the output is like this:

输出是:

长度:10

长:5

长度:2

长度:1

为什么我收到这样的;如果我想采取从一个阵列整个数据到另一个阵列的我该怎么办?

why I am getting like this; If I want to take the entire data from one array to another array the how can I do?

建议我如果有人知道。

推荐答案

阵列衰变在函数调用指针。这是不可能计算数组的大小,这是只有重新psented为以任何方式的指针,包括使用$ P $ 的sizeof

Arrays decay to pointers in function calls. It's not possible to compute the size of an array which is only represented as a pointer in any way, including using sizeof.

您必须添加一个明确的说法:

You must add an explicit argument:

void show(int *data, size_t count);

在通话时,您可以使用的sizeof 来计算元素的数量,实际数组:

In the call, you can use sizeof to compute the number of elements, for actual arrays:

int arr[] = { 1,2,3,4,5 };

show(arr, sizeof arr / sizeof *arr);

注意的sizeof 给你的大小字符的单位,这就是为什么除以本质上是的sizeof(INT)是必要的,否则你会得到一个太高的价值。

Note that sizeof gives you the size in units of char, which is why the division by what is essentially sizeof (int) is needed, or you'd get a way too high value.

另外请注意,兴趣和清洁一个点,即的sizeof 是的的功能。当参数是一个类型的名字时,才需要括号,因为参数则是一个铸像前pression(例如的sizeof(INT))。你经常可以逃脱不会对数据命名实际类型,通过执行的sizeof 代替。

Also note, as a point of interest and cleanliness, that sizeof is not a function. The parentheses are only needed when the argument is a type name, since the argument then is a cast-like expression (e.g. sizeof (int)). You can often get away without naming actual types, by doing sizeof on data instead.

这篇关于如何获得数组在C的长度?是&QUOT; sizeof的&QUOT;是溶液中的一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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