My code isn’t working clearly. I want to give a random size to pointer and I want to add some elements to the pointer. I want to give place to the pointer enough size. For example, if I have 10 elements in pointer, I want to give place 40 byte to pointer. But when I looked to my code ,initially I gave so much size for the element. I want to see as an output:
67
11
64
7
67
11
64
7
23
81
88
35
12
5
7
the size of memory=40
#include <stdio.h>
#include <stdlib.h>
int main() {
int *k;
int i=0,j=0,t=0;
int array[20]={67,11,64,7};
k=malloc(5*sizeof(int));
k=array;
for(i=0;i<4;i++){
printf("%d\n",k[i]);
}
k=realloc(k,50*sizeof(int));
k[4]=23;
k[5]=81;
k[6]=88;
k[7]=35;
k[8]=12;
k[9]=5;
k[10]=7;
for(j=0;k[j]!='\0';j++){
printf("%d\n",k[j]);
}
k=realloc(k,(j+1)*sizeof(int));
for(t=0;k[t]!='\0';t++){
printf("%d\n",k[t]);
}
printf("the size of the memory=%d \n",j*4);
printf("the size of the memory=%d \n",t*4);
return 0;
}
>Solution :
You can’t resize an automatic variable like array which is what you are trying to do since you do k=array; (and leak the memory previously allocated).
You can copy the data from array into the allocated memory pointed out by k instead:
int array[20] = {67, 11, 64, 7};
int *k = malloc(sizeof array);
memcpy(k, array, sizeof array);
The loop condition you use is a tad confusing though:
for (j = 0; k[j] != '\0'; j++)
I suggest comparing with 0 instead.
The "the size of the memory" that you print out at the end is however not accurate. The size of the allocated memory at the end is (j+1)*sizeof(int), that is, 12 * sizeof(int), since k[11] is the first element being 0.
Note: Don’t forget to free(k); when you’re done with it.