0
我試圖使用嚴格指針算術將數值從一個數組複製到另一個數組。這是我現在的代碼:如何使用指針算術將數組中的值從一個數組複製到另一個數組
int *p;
int arraySize = 20;
int array[arraySize];
for (p = array; p< array+(sizeof(array)/sizeof(int)); p++){
int random = rand() % 200;
*p = random;
}
for (p = array; p< array+(sizeof(array)/sizeof(int)); p++){
printf("%d\t%x\n", *p, p);
}
//the code above works fine
printf("\n");
//grow the new array by one to insert value at end later
int array2[(arraySize+1)];
int *p2;
for(p2 = array2; p2< array2+(sizeof(array2)/sizeof(int)); p2++){
*(p2) = *(p);
}
for(p2 = array2; p2< array2+(sizeof(array2)/sizeof(int)); p2++){
printf("%d\t%x\n", *p2, p2);
}
但是,當我運行代碼所有輸出在每個內存位置是0。我做錯了什麼是防止值被複制過來?
「p」不會遞增。 –
你的代碼存在的問題是它改變了'p2',但它永遠不會改變'p'。投票結束爲錯字。 – dasblinkenlight
做p ++給出的隨機數與一些零混合在內存位置輸出 – theplaid