c - 根据用户定义的数组长度存储数组值

标签 c arrays scanf

<分区>

基本上,我试图编写一个简单的 C 函数,提示用户输入数组长度,然后要求用户输入数组的值(整数)。

所需的示例输出:

Enter Array Length: 5
Enter values for the array:
1 2 3 6 7

The current array is:
1 2 3 6 7

这是我目前的代码。我觉得这应该行得通,但由于对 C 语言有如此基本的了解,它会导致段错误。

int intersect()
{
  int size, index, input;
  printf("Enter the size of the arrays:\n");
  scanf("%d", &size);

  int arr1[size], arr2[size];
  index = 0;
  printf("Enter the elements of the first array:\n");
  while (index < sizeof(arr1))
    {
      scanf("%d ", &input);
      arr1[index] = input;
      index = index + 1;
    }

  printf("The current array is:\n %d", arr1);
}

我不明白如何为用户定义长度的数组收集输入。任何解释表示赞赏!

最佳答案

sizeof 以字节为单位返回占用的内存,而不是数组长度。所以基本上您是在检查索引是否小于 40(整数大小 * 数组长度)。由于该数组没有空间来存储 40 个整数值,因此它给出了未定义的行为(某些时间段错误)。

你应该改为更改

while (index < sizeof(arr1))

while (index < size)

第二个也是正确的:

printf("The current array is:\n %d", arr1);
//                               ^    ^  address             

作为

for (i = 0; i < size, i++)  
  printf("The current array is:\n %d", arr1[i]);

要么打印地址使用%p

关于c - 根据用户定义的数组长度存储数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18951151/

相关文章:

PHP逆时针旋转矩阵

c - Fscanf 不复制到字符串

c - 带有 c 型类型转换的 GCC 警告

c - createprocess 函数的困难时期

c - 为什么我的按钮在使用 C 的 SDL2 中不起作用?

ios - 在 swift 3 中将字节数组转换为 PDF

c - 可执行和可重定位目标文件中的疑问

PHP 数组 : renumber elements when new element added

c - 将 fscanf 转换为 C 中的二维数组

c - 包含字母、空格和整数的 sscanf