Initialize structure C via function

Therefore, I need to write a type data structure vectorin C. In general, I created this structure:

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, a function initialize_vector(), I just wanted to initialize the attributes of the default vectors (for example, from lengthto 0 *elementsto 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 the GDB, and, of course, when all fastens this line: vector->elements = NULL;.

, . , , , . , , , , uberprogrammieren , , , .

+4
2

, . , undefined .

struct Vector :

struct Vector vec;
initialize_vector(&vec);
printf("%d\n", vec.length);

struct Vector , malloc :

struct Vector *initialize_vector()
{
    struct Vector *vector = malloc(sizeof(*vector));
    if (!vector) {
        perror("malloc failed");
        exit(1);
    }
    vector->elements = NULL;
    vector->length = 0;
    return vector;
}

...

struct Vector *vector = initialize_vector();
+10

dbush , . C-, .

struct Vector * vec;

, . ? , . , , , int *, char *, char ** struct Vector *, ( 32 64 ). ( , ). , void * . , : "vec - , Vector". , , vec .

, , , , . initialize_vector(), , . , , - . seg.

, , , . , ( malloc) ? , , , , . , , , . dbush. , free().

+1

Source: https://habr.com/ru/post/1679376/


All Articles