Malloc an array inside a struct

The problem is that you're allocating space for the string, but you're not allocating the struct at all. c remains set to NULL and you're trying to dereference it.

Allocate space for the struct before assigning to its members

prod_t *c = malloc(sizeof(prod_t));

And, as a sidenote for your next-to-fix error: this field doesn't exist

c->stock

You need to allocate space for the struct before you can assign to the string member:

prod_t *c = malloc(sizeof(prod_t));

Also see Do I cast the result of malloc?


First of all, don't cast result of malloc. You only need to do that in C++. In C, it can actually hide potential problems.

Second of all, you need to allocate (or statically declare) your structure.

Third, c->stock doesn't exist. You probably meant c->string.

typedef struct {
    char *string;
} prod_t;

int
main(int agrc, char **argv) {
    int i = 0;
    prod_t *c = malloc( sizeof( prod_t ));


    char str2[100] = "abcd";
    c->string = malloc( 5 * sizeof(char));
    strcpy(c->string,str2);

    compares(c->string,str2,i);

    return 0;
}