基本上,我试图编写一个简单的C函数,提示用户输入数组长度,然后要求用户输入数组的值(int).
样本输出所需:
Enter Array Length: 5
Enter values for the array:
1 2 3 6 7
The current array is:
1 2 3 6 7
Run Code Online (Sandbox Code Playgroud)
这是我目前的代码.我觉得好像这应该有效,但是基于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);
}
Run Code Online (Sandbox Code Playgroud)
我不明白如何收集用户定义的长度数组的输入.任何解释都表示赞赏!
sizeof返回以字节为单位的内存而不是数组长度.所以基本上你要检查索引是否小于40(size of Integer * array length).由于数组没有空间来存储40个整数值,因此它给出了未定义的行为(一些时间分段错误).
你应该改变
while (index < sizeof(arr1))
Run Code Online (Sandbox Code Playgroud)
至
while (index < size)
Run Code Online (Sandbox Code Playgroud)
第二个也正确:
printf("The current array is:\n %d", arr1);
// ^ ^ address
Run Code Online (Sandbox Code Playgroud)
如
for (i = 0; i < size, i++)
printf("The current array is:\n %d", arr1[i]);
Run Code Online (Sandbox Code Playgroud)
要么打印地址使用%p.