为什么数组值与C程序中指定的值不同
我编写了一个小代码,它接受一个10个值的数组,将数组传递给一个函数,该函数将每个值加倍。数组打印函数中的预期值(双精度)。回到main函数中,输出printed在for循环中有索引1、2和3的垃圾值,用于打印所有值。为什么这些值会改变?主函数和被调用函数的地址都相同为什么数组值与C程序中指定的值不同,c,arrays,C,Arrays,我编写了一个小代码,它接受一个10个值的数组,将数组传递给一个函数,该函数将每个值加倍。数组打印函数中的预期值(双精度)。回到main函数中,输出printed在for循环中有索引1、2和3的垃圾值,用于打印所有值。为什么这些值会改变?主函数和被调用函数的地址都相同 StructA doubleArray(int* alist, int b) { StructA doubled; int temp[b]; for(int i=0; i < b; i++){
StructA doubleArray(int* alist, int b) {
StructA doubled;
int temp[b];
for(int i=0; i < b; i++){
temp[i] = 2 * alist[i];
}
doubled.a = temp;
doubled.b = b;
return doubled;
}
int main() {
int arange[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int len = 10;
StructA hasDoubledValues = doubleArray(arange, len);
printf("\nvalues in main :");
for(int k = 0; k < hasDoubledValues.b; k++){
printf(" %d \n", hasDoubledValues.a[k]);
}
return 0;
}
StructA doubleArray(int*alist,int b){
结构加倍;
内部温度[b];
对于(int i=0;i
其打印值为:0-1434592 32507 8 10 12 14 16 18
我希望这些值是:
02468104141618
inttemp[b]代码>是函数的本地代码。
一旦您从函数返回,该内存的生命周期将停止,访问它将产生未定义的行为。@xing谢谢。这工作正常