'How to give a size using realloc? [closed]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
