I am trying to have dynamically allocate arrays of structures and perform operations on them but i keep running into segmentation faults. could someone help me out?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void *malloc(size_t size);
typedef struct {
double x;
double y;
} coords;
struct figure {
char fig_name[128];
int coordcount, size_tracker;
coords *pointer;
} fig;
void init_fig(int n, struct figure **point)
{
printf("%u\n", sizeof(coords));
point[n]->pointer = malloc(sizeof(coords) * 20); <-------SEGFAULT
if (point[n]->pointer == NULL){
exit(-1);
}
point[n]->pointer[19].x = 2;
point[n]->pointer[0].x = 1;
point[n]->pointer[0].y = 2;
point[n]->pointer[7].x = 100;
}
int main()
{
int numfigs = 1;
struct figure * point;
point = malloc(sizeof(struct figure) * 16);
point = &fig;
point[1].coordcount = 1;
init_fig(numfigs, &point);
return 0;
}
I labelled where the first seg fault occurs, (used ddd). what i dont get is that i can manipulate point[1] in main but not in any other function.
I agree with @Maxim Skurydin.
Nevertheless I’d like to explain your mistake in some more details.
Reading your
init_figone assumes that the parameter you passstruct figure **point– is actually array of pointers tostruct figure. And this function accesses itsn‘th element.However in your
mainyou do something else. You allocate an array ofstruct figure, and yourpointvariable points to its head. Then you take the address of this local variable and call yourinit_fig.Here’s the problem.
init_figassumes that you pass it an array of pointers, whereas actually this “array” consists of a single element only: the localpointvariable declared inmain.EDIT:
How to do this properly.
mainintact, fixinit_fig.This means that actually there’s an array of
figurestructs. Means – a single memory block, interpreted as an array of consequent structs.init_figintact. Fixmain.This means that we actually should allocate an array of pointers, every such a pointer should point to an allocated
pointstructure.