【发布时间】:2017-05-08 17:10:13
【问题描述】:
我正在尝试使用严格的指针算法将值从一个数组复制到另一个数组。这是我现在的代码:
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。投票结束是一个错字。 -
执行 p++ 将随机数与一些零混合作为内存位置的输出
-
Eugene 和 das 都发现了问题;我只是来问——为什么要这样?当您使用
[x]语法时,*(ptr + (x * sizeof(int)))正是编译器正在执行的操作(其中int是数组类型,如本例)... -
因为这是我们作业的要求。但是当用 p++ 递增 p 时,它没有给出正确的输出......
标签: c arrays pointers pointer-arithmetic