我正在学习C,我的一个函数(这里没有显示)依赖于两个数组是相同的.我有一个数组,我正在尝试生成一个副本,但会发生的是,两个数组在复制后都变成了0.我不知道这是怎么发生的.任何人都可以帮助解释为什么会发生这种情况并提供一个如何做到正确的解决方案?
#include <stdio.h>
int main(){
int array[5]={3,2,7,4,8};
int other_array[5]={0,0,0,0,0};
for (int i=0; i<5; i++) array[i]=other_array[i]; //Copies array into other_array
printf("array is:\n");
for (int j=0; j<5; j++) printf("%d", array[j]);
printf("\nother_array is:\n");
for (int i=0; i<5; i++) printf("%d", other_array[i]);
printf("\n");
return 0;
}
/*
When run this yields
**********************
array is:
00000
other_array is:
00000
*/
Run Code Online (Sandbox Code Playgroud)
//Copies array into other_array
for (int i=0; i<5; i++) array[i]=other_array[i];
Run Code Online (Sandbox Code Playgroud)
尝试:
other_array[i] = array[i];
Run Code Online (Sandbox Code Playgroud)
赋值运算符将右操作数的值分配给左操作数中的对象.而不是相反.
另外,如其他答案所述:
printf("\nother_array is:\n");
for (int i=0; i<5; i++) printf("%d", array[i]);
Run Code Online (Sandbox Code Playgroud)
你是打印array
而不是other_array
.