I am trying to write a simple program in C that stores elements in a pointer. I am getting junk values when I print the elements of the array.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
int main(int argc, char const *argv[]) {
int* a = (int*)malloc(MAX * sizeof(int));
int* b = NULL;
int* const maxAddress = a + MAX;
if(a != NULL) {
for(int index = 0; b = a, b < maxAddress; index++) {
*(a + index) = index;
printf("Value: %d, Index: %d\n", *(a + index), index);
a++;
}
}
printf("\n\n");
for(int index = 0; index < MAX; index++) // Getting junk values here
printf("Index: %d, Value: %d, Address: %p\n", index, *(a + index), a + index);
return 0;
}