Realloc an int array
You need to pass a pointer to your pointers in add/begin so they can modify your pointer in main
begin(&n);
...
add(&n, i);
and your definition
void begin(int **n)
{
*n=malloc(sizeof(int));
if(*n==NULL)
{
printf("Error in malloc!");
return;
}
(*n)[0]=0;
printf("Added %d \n", (*n)[0]);
}
and
void add(int **n, int numToAdd)
{
static int sizeCount=0;
sizeCount++;
tempcount=sizeCount;
int *temp;
temp=realloc(*n, (sizeCount+1) * sizeof(int));
if(temp==NULL)
{
printf("Error in realloc!");
return;
}
*n=temp;
(*n)[sizeCount]=numToAdd;
printf("Added %d \n", (*n)[sizeCount]);
}
Right now what you're doing is modifying local copies of your pointer in begin/add, so when you change it in those functions it's not modifying your pointer n
in main
Also, fun fact, if you pass NULL
as the first parameter to realloc
it acts like a malloc
, so if you initialize n
to NULL
, you can simply call add
without first doing a begin
.
Draconian Times
Updated on June 04, 2022Comments
-
Draconian Times almost 2 years
I'm trying to create an array to hold an int, then when another int is to be added increase it in size to hold another int.. and so on..
I know it's not an efficient use of realloc, but it's proof on concept more than anything else. Just to get it working would allow me to optimise it and be able to apply it to something useful. A working example. The problem comes when i call the print function and it just segfaults. Any help would be appreciated.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> typedef char String[100]; void begin(int *); void add(int *, int); void print(int *); int tempcount=0; int main(void) { int *n=NULL; String menu; begin(n); while(true) { scanf("%9s", menu); if(!strcmp("a", menu)) //add { int i=0; scanf("%d", &i); add(n, i); } else if(!strcmp("p", menu)) //print { print(n); } else if(!strcmp("q", menu)) //quit { free(n); break; } } return 0; } void begin(int *n) { n=malloc(sizeof(int)); if(n==NULL) { printf("Error in malloc!"); return; } n[0]=0; printf("Added %d \n", n[0]); } void add(int *n, int numToAdd) { static int sizeCount=0; sizeCount++; tempcount=sizeCount; int *temp; temp=realloc(n, (sizeCount+1) * sizeof(int)); if(temp==NULL) { printf("Error in realloc!"); return; } n=temp; n[sizeCount]=numToAdd; printf("Added %d \n", n[sizeCount]); } void print(int *n) { int i; for(i=0; i<tempcount; i++) { printf("%d ", n[i]); } }