我的代码有问题,输入的值会导致崩溃n
。
我已经输入了我认为代码应该执行的操作。
我猜指针存在问题*a[i]
,导致程序崩溃。
#include <stdio.h>
#include <stdlib.h>
void assign_zero(int * a[], int * n){ // fetches value of a and n
int i;
for (i = 0; i < *n; i++)
*(a)[i] = 0; // puts every value in the array to 0 (a[3] = {0,0,0,0})
}
int main(){
int n;
printf("Choose value of n: ");
scanf("%i", &n); // stores the int at n's adress
int a[n]; // sets the length of the array
assign_zero(&a, &n); // sends the adress of a and n to assign_zero
int x;
for (x = 0; x < n; x++)
printf("%i", a[x]); // prints 00000... depending of n's value
return 0;
}
在通话中,您正在使用
assign_zero(&a, &n);
称呼。但是功能签名是
void assign_zero(int * a[], int * n)
在这种情况下,这似乎是错误的。您只需要一个指针来保存传递的数组,例如
void assign_zero(int * a, int * n)
就足够了。然后,在函数中,您可以直接使用a[i]
来访问数组的元素。
也就是说,似乎您没有在修改n
fromassign_zero()
函数的值。如果是这种情况,则无需将其作为指针传递。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句