为了使用指针算术循环遍历常规 int 数组,如下所示:
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);
}
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);
}
但是,我要声明:
int *array = (int*) calloc(arraySize, sizeof(int));
我对如何循环动态分配的内存而不是常规的静态数组感到非常困惑。
最佳答案
int *array = (int*)calloc(arraySize, sizeof(int));
int *array_end = array + arraySize;
int* ptr;
for(ptr = array; ptr < array_end; ptr++)
printf("%p\t%d", ptr, *ptr);
关于c - 如何使用指针算术循环分配的内存 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43856010/