在c中查找char数组和int数组的长度[关闭]

问题描述 投票:0回答:2

我是 C 编程语言新手。
我刚刚了解了使用 sizeof() 内置函数。
当涉及到整数数组时,通过放置

int length = sizoeof(arrayname[0]); /* gives the length of the array*/

然而,对于字符数组,它仅产生 1:
int length = sizeof(arrayname2[0]); /* it gives only one character and i have as sting in it*/

int main(void)
{
    int numArray[] = {2,4,6,8,10,12}; char school[] = "Aquinas";
    int length;
    length = sizeof(numArray[0]) ;
    length = sizeof(school); 
}

我期望得到与整数数组相同的结果。
顺便说一下,我们无法使用

strlen()

arrays c sizeof
2个回答
0
投票

如果对整数使用 sizeof() 函数,该函数将为每个整数返回 4。这是因为 int 变量通常在内存中占用 4 个字节。因此,该函数为每个整数返回 4。

另一方面,对于 char,该函数将返回 1。这是因为 char 变量在内存中仅占用 1 个字节。因此,sizeof() 函数将为每个字符返回 1。


0
投票

sizeof(numArray[0])
不会产生数组
numArray
的大小。该表达式相当于
sizeof( int )
,给出数组元素的大小。

sizeof( char )
始终等于
1

Tp 获取您需要写入的数组的大小

size_t length1 = sizeof(numArray );
size_t length2 = sizeof( school ); 

要计算数组中元素的数量,您可以编写

size_t n1 = sizeof(numArray ) / sizeof( numArray[0] );
size_t n2 = sizeof( school ) / sizeof( school[0] );

虽然

sizeof( char )
等于
1
那么最后一行可以像

一样重写
size_t n2 = sizeof( school );

字符数组中存储的字符串长度等于

sizeof( school ) - 1

© www.soinside.com 2019 - 2024. All rights reserved.