2

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.

1
  • 3
    Replace every (sizeof(array)/sizeof(int)) with arraySize and both should function as you desire. Commented May 8, 2017 at 20:00

1 Answer 1

2
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);
Sign up to request clarification or add additional context in comments.

1 Comment

code only answers are not all that useful. Please try to add some explaination.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.