在 C 中更改函数内部的数组 [英] Changing array inside function in C
问题描述
我正在学习 C 并困惑为什么在 main 中创建的数组不会在函数内部更改,我假设传递的数组是一个指针,并且更改指针应该更改数组,对吗?有人可以解释一下在这种情况下发生了什么吗?
I am learning C and confused why a array created in the main wont change inside the function, i am assuming the array passed is a pointer, and changing the pointer should've change the array , right ? can someone explain what is happening in this case?
感谢您的帮助.
int main(){
int i, length = 10;
int array[length];
for (i = 0 ; i < length ; i++)
array[i] = i * 10;
printf("Before:");
print(array, length);
change(array, length);
printf("After:");
print(array, length);
return 0;
}
// Print on console the array of int
void print(int *array,int length)
{
int i;
for(i = 0 ; i < length ; i++)
printf("%d ", array[i]);
printf("\n");
}
// Change the pointer of the array
void change(int *array,int length)
{
int *new = (int *) malloc(length * sizeof(int));
int i;
for(i = 0 ; i < length ; i++)
new[i] = 1;
array = new;
}
我希望看到以下输出:
Before:0 10 20 30 40 50 60 70 80 90
After:1 1 1 1 1 1 1 1 1 1
我得到了什么:
Before:0 10 20 30 40 50 60 70 80 90
After:0 10 20 30 40 50 60 70 80 90
推荐答案
在 c 你不能通过引用传递变量,你在函数内部分配的 array
变量最初包含与传递的指针相同的地址,但它是它的副本所以修改它不会改变传递的指针.
In c you can't pass a variable by reference, the array
variable that you assign inside the function contains initially the same address as the passed pointer, but it's a copy of it so modifying it will not alter the passed pointer.
你需要传递指针的地址才能改变它,就像这样
You need to pass the address of the pointer in order to be able to alter it, like this
// Change the pointer of the array
void change(int **array, int length)
{
*array = malloc(length * sizeof(int));
if (*array == NULL)
return;
for (int i = 0 ; i < length ; i++)
(*array)[i] = 1;
}
然后在 main()
中你不能赋值给一个数组,通过这种函数这样做肯定是未定义的行为.main()
中定义的数组在堆栈上分配,您不能为数组分配任何内容,因为它们是不可可写的左值,因此您不能让它指向用malloc()
获得的堆内存位置,你需要像这样传递一个指针
Then in main()
you cannot assign to an array, doing so through this kind of function is surely undefined behavior. The array defined in main()
is allocated on the stack and you cannot assign anything to an array since they are non-writeable lvalues so you cannot make it point to a heap memory location obtained with malloc()
, you need to pass a pointer like this
int *array;
change(&array, length);
free(array);
如果你想让函数替换之前的数组,它必须free()
malloc()
ed 数据(注意传递NULL
到 free()
是明确定义的),所以
If you want the function to replace the previous array, it will have to free()
the malloc()
ed data (note that passing NULL
to free()
is well defined), so
// Change the pointer of the array
void change(int **array, int length)
{
free(*array);
*array = malloc(length * sizeof(int));
if (*array == NULL)
return;
for (int i = 0 ; i < length ; i++)
(*array)[i] = 1;
}
然后在 main()
int *array;
array = NULL;
change(&array, length);
change(&array, length);
change(&array, length);
change(&array, length);
free(array);
会做你显然想要的.
这篇关于在 C 中更改函数内部的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!