``````int x = 0;
int i,j,p;
int buf;
int *array = {0};
for (j = 0; j < 3; j++){
for (i = 0; i <4; i++) {
buf[i] = x++;
}
array[j] = buf;
}
int* temp;
temp = array;
for (i = 0; i<4; i++)
{
printf("%d\n", *temp);
temp++;
}
``````

I expect to get 4,5,6,7
but i get 8,9,10,11

I know whats wrong though, array is merely pointing to buf, it isnt copying the data from buf, so when the data from buf changes so does array[] since it points to it

My question is: is there a way to do this? I've tried very ways but i cant seem to wrap my head around it

Try this:

``````    int x = 0;
int buf;
int* array;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
buf[j] = x++;
}
array[i] = (int*)malloc(sizeof(buf));
memcpy((void*)array[i], (void*)buf, sizeof(buf));
}

for (int i = 0; …``````

Good question. Yes, you would have to iterate the array and call free on each element that was malloc'd. However, if this is the extent of your program, you really don't need to as the system will clear the heap for you on exit of the program.

## All 5 Replies

Try this:

``````    int x = 0;
int buf;
int* array;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
buf[j] = x++;
}
array[i] = (int*)malloc(sizeof(buf));
memcpy((void*)array[i], (void*)buf, sizeof(buf));
}

for (int i = 0; i < 5; i++)
{
int* temp = array[i];
for (int j = 0; j < 4; j++)
{
printf("%d\n", temp[j]);
}
}
``````

Bear in mind that some older compilers will object to the second outside `for(int i = 0; i < 5; i++)` as they don't properly scope the variable declared in the for() loop to just that loop.

when i call free, would free(array)work or would i have to run a for loop on free(array[i])

Good question. Yes, you would have to iterate the array and call free on each element that was malloc'd. However, if this is the extent of your program, you really don't need to as the system will clear the heap for you on exit of the program.

commented: thanks alot for the help, solved a problem i was struggling with for a few hours +0

Hi! rubberman, can you please explain what was the cause of error in original code.

Thanks

can you please explain what was the cause of error in original code.

Try reading the original post. It includes a description of the problem: "I know whats wrong though, array is merely pointing to buf, it isnt copying the data from buf, so when the data from buf changes so does array[] since it points to it"

The cause of the error is obviously multiple pointers aliasing a single array when the intention was clearly for each pointer to reference a unique array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.