Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to give a size using realloc?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading