Search code examples
arrayscstructsegment

C Array in Struct - Segmentation fault


I am trying to get a better knowledge of C and I am currently writing and experimenting with different code snippets. The actual one is making me crazy because I have no idea what I need to change so it will work.

I want to store something into a struct as a char array, but when I want to read the stored char array, I always get a segmentation fault.

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

struct connector {
    char *subject;
};

int main() {
    char *subject = NULL;
    struct connector *conn;
    subject = "TEE";
    printf("%s\n", subject);
    
    conn->subject = subject;
    
    printf("%s\n", conn->subject);
    
    return 0;
}

So why the second printf is having this problem ?


Solution

  • You have a struct pointer struct connector *conn which was not initialized.

    You may declare it on the stack struct connector conn; or allocate a memory for it with malloc as follows: struct connector *conn = (struct connector *)malloc(sizeof(struct connector));.