#Learning to use malloc and realloc having issues.

8 messages · Page 1 of 1 (latest)

normal tusk
#

Why does it reallocate the first 10 indexes as well?? Tutorial I've been following doesn't have this issue and I can't see with my own eye why it's not working so could someone take a look and see if they could point me in the write direction.

opaque mirageBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

normal tusk
#

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int main() {
int a_size = 10;
int *a = NULL;

a = malloc(a_size * sizeof(int));
        
if(a == NULL) {
    fprintf(stderr, "Error allocating memory!\n");
    exit(1);
}

for(int i=0; i<a_size; i++) {
    a[i] = i*10;
}


int *tmp = NULL;
int new_a_size = a_size*2;

tmp = realloc(a,new_a_size*sizeof(int));

if (tmp==NULL){
    fprintf(stderr,"Erorr realoccating a!\n");
    exit(1);
}

a = tmp;

for (int i=10;i<new_a_size;i++){
    a[i]=i*10;
}

for (int i=0;i<new_a_size;i++){
    printf("a[%d]: %d\n");    
}

free(a)

return 0;

}

#

code

#

!solved never mind I forgot to put in the variables I wanted to subsite for the format modifiers my bad

opaque mirageBOT
normal tusk
#

!solved

opaque mirageBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity