I wanted to copy the first half of my dynamic array into the second half of the same array, but the output here is from ptr[100] to ptr[200] 9.90. I think I coded everything fine but I dont know where the problme is. Can you help me?
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int i;
int j;
double * ptr = calloc(100, sizeof(double));
if (ptr == NULL)
return 0;
for(i = 0; i < 100; i ) {
ptr [i] = i / 10.0;
}
for(i = 0; i < 100; i ) {
printf("ptr[%d] = %.2f\n", i, ptr[i]);
}
if (realloc(ptr, 200) == NULL)
return 0;
for (i = 0; i < 100; i )
for (j = 100; j < 201; j )
ptr [j] = ptr[i];
for (j = 100; j < 201; j )
printf("ptr[%d] = %.2f\n", j, ptr[j]);
return 0;
}
CodePudding user response:
You are underallocating on the realloc. You didn't make enough space for 200 doubles, so attempting to access ptr[x]
is undefined behavior for values of x > 99. Also, realloc
may move the memory, so you need to assign the new value back to ptr
. For example:
ptr = realloc(ptr, 200 * sizeof *ptr);
if( ptr == NULL ){
perror("realloc");
exit(1);
}
And after this, accessing ptr[200]
is undefined behavior. You need to reduce the scope of the loop index to for( j = 100; j < 200; j )
CodePudding user response:
You are overwriting for every copy
for (i = 0; i < 100; i ) // for every item in the first half
for (j = 100; j < 201; j ) // into every cell
ptr [j] = ptr[i];
shoud be
for (i = 0; i < 100; i )
ptr [i 100] = ptr[i];
and issue 2:
you didn't raallocate enough memory : change realloc(ptr, 200)
to realloc(ptr, 200 * sizeof(double))