我编写了一个程序来完成这些任务:首先从用户那里获取一个字符串,并使用 sizeof() 函数计算它的大小。这是我的代码:
#include <stdio.h>
int main()
{
char U1[];
puts("Enter a string:");
scanf("%s", U1);
printf("The %s has %i bytes.", U1, sizeof(U1));
return 0;
}
编译错误为:error: array size missing in ‘U1’
为什么 ?请解释一下这里出了什么问题?
最佳答案
您需要定义数组大小来告诉编译器要分配多少空间:
char U1[256];
如果您在编译时不知道数组的大小,可以使用 malloc
动态分配内存。 :
// #include <stdlib.h>
int *arr;
int n, i;
printf("Number of elements: ");
scanf("%d", &n);
// Allocate n ints
arr = malloc(n * sizeof(int));
printf("Enter %d elements: ", n);
for(i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Here they are: ");
for(i = 0; i < n; i++)
printf("%d ", arr[i]);
// Free the array on the end!
free(arr);
注意
printf("The %s has %i bytes.", U1, sizeof(U1));
将始终打印 256,如 sizeof
返回编译时扣除的数组大小,而不是刚刚读入数组的字符数。您可以使用 sizeof(char) * (strlen(U1) + 1)
计算字符串所需的字节数(+1 来自字符串末尾的 NUL 终止符)。
关于c - C 中的数组大小错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18850091/