gpt4 book ai didi

c - 为什么我的函数会更改输入参数的值?

转载 作者:太空宇宙 更新时间:2023-11-04 07:53:17 25 4
gpt4 key购买 nike

可变长度数组是不允许的。但是后来,我最近了解到用户定义函数操作的是原始数组,而不是它自己的个人副本。所以我想创建一个函数,由用户获取所需的数组大小,从而修改大小(我也在这个函数中初始化了数组)。

void fill_array(int array[], int size, int in_val);

void main(){
int n, value, list[1], ctr;
clrscr();

printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the value that you want all of the elements to take initially: ");
scanf("%d", &value);
printf("\nAfter scanning value, n = %d\n", n);

fill_array(list, n, value);

printf("\nAfter Function fill_array Execution");
printf("\nThe values of each element of the array is now: %d ", list[0]);
printf("%d ", list [1]);
printf("%d ", list [2]);
printf("\nn = %d\n", n);
printf("value = %d\n", value);

getch();
}

void fill_array(int array[], int size, int in_val){
int ctr;

for (ctr = 0; ctr < size; ++ctr)
array[ctr] = in_val;
printf("\nInside Function");
printf("\nn = %d\n", size);
printf("value = %d\n", in_val);
}

这是控制台/示例运行:

Enter the size of the array: 3

Enter the value that you want all of the elements to take initially: 444

After scanning value, n = 3

Inside Function

n = 3

value = 444

函数 fill_array 执行后

现在数组每个元素的值是:444 444 444

n = 444

值 = 444

该函数确实修改了 list。但是,如您所见,它还更改了 n 的值。在每次 fill_array 执行后,n 总是等于 value。请有人向我解释为什么该函数正在更改 n 的值。我不想改变 n 的值。

最佳答案

fill_array 函数中,您试图写入超出 list 数组范围的内存。这样做会导致未定义的行为。

来自 undefined behaviour 上的维基文章:

The behavior of some programming languages—most famously C and C++—is undefined in some cases. In the standards for these languages the semantics of certain operations is described as undefined. These cases typically represent unambiguous bugs in the code, for example indexing an array outside of its bounds.

C 委员会草案 (N1570) 关于未定义行为的说明:

3.4.3
1 undefined behaviour
behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements
2 NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

关于c - 为什么我的函数会更改输入参数的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52437890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com