So I do have to write a vector-like data structure in C. Generally I made a structure like this:
struct Vector { int length; int *elements; }; And functions like these:
void initialize_vector(struct Vector* vector); void create_vector(struct Vector* vector, int* array, int n); void remove_vector(struct Vector* vector); void vector_add_element(struct Vector* vector, int element); void vector_insert(struct Vector* vector, int index, int element); void vector_remove_element(struct Vector* vector, int element); void vector_remove_at(struct Vector* vector, int index); Now, the initialize_vector() function, I wanted it just to initialize vectors attributes to default values (like length to 0 and *elements to NULL). I wrote something like this:
void initialize_vector(struct Vector* vector) { vector->elements = NULL; vector->length = 0; } And I tried to check if it works, so I wrote this piece of code:
#include <stdio.h> #include "vector.h" int main(int arc, char** argv) { struct Vector* vec; initialize_vector(vec); printf("%d\n", vec->length); return 0; } I got famous Segmentation fault, so I checked on GDB, and of course the moment when everything screws up is this line: vector->elements = NULL;.
I don't know where the problem is. I declare a vector, I pass it properly I guess and it messes up. I know that is probably trivial and I will get massively downvoted by some uberprogrammieren guys, but hey, he that nothing questioneth nothing learneth.
struct Vector* vec;tostruct Vector vec;initialize_vector(vec);toinitialize_vector(&vec);to pass the function a pointer to the structure. 2: Create an instance to a Vector with malloc().struct.struct Vector. A pointer is not the same as the type it points to! Details are essential in programming! "the moment when everything screws up is this line …" - You screwed up much earlier! Compiler warnings are not for fun! Enable them and pay heed!