c - C 中的数组大小错误

标签 c arrays

我编写了一个程序来完成这些任务:首先从用户那里获取一个字符串,并使用 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/

相关文章:

java - 如何用Python、C或Java读取大数据文件的一部分?

php - 组合数组但保留键?

C++,数组大小必须是一个常量表达式

我可以创建一个函数,它接受一个指向数组的指针,该数组在每次调用时可能包含不同类型的数字吗?

c - Valgrind:条件跳转或移动取决于未初始化的值(指针的指针)

c - 自己版本的 strncpy 不应该工作,但它确实有效

java - 返回 Java 数组与集合

java - 我无法打印二维数组中的最后一列

c - 如何定义跨多个 .c 文件可见的全局变量

c - C 中的低级函数调用?