0

I don't know how to add multiple values for a struct in C using a pointer. Here's my code and the gcc error is:

error: assignment to expression with array type (p+0)->name = "Teszt";

#include <stdio.h>

typedef struct{
    char name[101];
    int born_in;
} paciens;

int main(){
    paciens *p;
    int n = 5;
    p = (paciens*) malloc(n * sizeof(paciens));

    (p+0)->name = "Test";
    (p+0)->born_in = 1992;

    printf("Name: %s ; Born in: %d\n", (p+0)->name, (p+0)->born_in);
    return 0;
}
2
  • 1
    (p+0)->name = "Test"; ==> strcpy((p+0)->name, "Test"); Commented Oct 15, 2018 at 14:10
  • The section in your reference text/site on how to copy strings in C would be a good place to start (or any of the thousands of hits google will return on the same subject). Commented Oct 15, 2018 at 14:11

2 Answers 2

1

You cannot assign to an array, but you can assign to a struct, which contains an array:

p[0] = (paciens) { .name = "Test", .born_in = 1992};

will do this. This is called a compound literal.

https://ideone.com/f99rUF

Also note that you forgot to #include <stdlib.h> for malloc.

Sign up to request clarification or add additional context in comments.

Comments

0

The member name is an array. You can't assign to an array, only copy to it. To copy a string use strcpy:

strcpy(p[0].name, "Test");

Any good book, tutorial or teacher should have mentioned this.

3 Comments

Any other method where we dont use <string.h> library?
@32icHARD Well char strings in C are really called null-terminated byte strings. It's easy to implement your own variant of strcpy with a simple loop if you remember the proper name. But I fail to see why anyone would want that.
Thanks a lot, have a nice day! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.