根据用户定义的数组长度存储数组值 [英] Store Array Values from User Defined Array Lengths

查看:34
本文介绍了根据用户定义的数组长度存储数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Basically, I am attempting to write a simple C function that prompts the user for an array length, and then asks the user to input values (ints) for the array.

所需的样本输出:

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

The current array is:
1 2 3 6 7

此刻是我的代码.我觉得这应该可行,但是具有C的基本知识,这会导致分段错误.

Here is my code at the moment. I feel as if this is should work, but with such a basic knowledge of C, it's causing a segmentation fault.

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);
}

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

I don't understand how to collect input for an array that is of length that a user defines. Any explanation is appreciated!

推荐答案

sizeof 返回以字节为单位的内存,而不是数组长度.因此,基本上,您正在检查index是否小于 40 ( Integer的大小*数组长度).由于数组没有空间来存储40个整数值,因此它给出了Undefined行为(某些时间分段错误).

sizeof returns the memory occupied in bytes and not the array length. So basically you are checking if index is less than 40 (size of Integer * array length). Since the array does not have space to store 40 integer values, it is giving Undefined behaviour ( some time segmentation fault).

您应该更改

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 .

这篇关于根据用户定义的数组长度存储数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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