我正在做一个大学项目,我已经在这部分停留了一段时间,似乎找不到答案。基本上,我们必须制作一个程序,使用按引用传递而不使用下标来填充数组(只是很烦人,因为他认为它们执行起来更快)。
到目前为止,这是我得到的:
这些是主要的相关部分:
#define SIZE 4
int *enteredCode;
enteredCode = (int*)calloc(SIZE, sizeof(int));
codeEnter(&enteredCode);
这是在头文件中:
//codeEnter function
void codeEnter(int **code){
//Declarations
system("cls");
puts("************* INPUT CODE *************"
"\n\nPlease enter your 4 digit code:");
for (int i = 0; i < SIZE; i++){
scanf("%d", *(code + i));
}//End of for
如果我将其更改为:
#define SIZE 4
int enteredCode[SIZE];
codeEnter(enteredCode);
标题部分:
void codeEnter(int *code){
//Declarations
system("cls");
puts("************* INPUT CODE *************"
"\n\nPlease enter your 4 digit code:");
for (int i = 0; i < SIZE; i++){
scanf_s("%d", &*(code + i));
}//End of for
}//End of codeEnter
如有任何帮助和解释,我们将不胜感激。
最佳答案
主要问题是如何在 codeEnter
函数中取消引用数组。
您正在传递一个指向 int
数组的指针,您需要获取数组中第 i 个元素的地址。
所以
void codeEnter(int **code) {
int* array = *code; // <- you obtain the original array
int* element = (array+i); // <- you obtain the address of the element
...
}
这个组合变成了*code + i
,而不是*(code+i)
。在您的代码片段中,您基本上修改了包含数组地址的地址(因此您获得了一个垃圾地址)。
关于c - 传递和更改数组,通过引用传递,使用 C 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28732911/