Reputation: 69
In order to loop through a regular int array with pointer arithmetic looks like such:
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);
}
However, I want to declare:
int *array = (int*) calloc(arraySize, sizeof(int));
I am very confused on how to loop through dynamically allocated memory as opposed to a regular static array.
Upvotes: 2
Views: 2509
Reputation: 537
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);
Upvotes: 2