-1

I can't figure out how to quickly initialize a bunch of structs. I'm getting stuck on needing to assign them a character array. The code is as follows:

typedef struct {
    char name[5];
} s;

s * buildS() {    
    char names[2][5] = { "name", "foo"};
    s stru[2];

    for (int i = 0; i < 2; i++) {
        s tmp;
        tmp.name = names + i;
        stru[i] = tmp;
    }

    return stru;
}

The s.name = names + 1; line is where the error appears:

error: incompatible types when assigning to type 'char[5]' from type 'char (*)[5]'

What am I missing here? Can I assign an internal array to a struct's array field?

Edit: fixed to crappy syntax in the code, my bad

6
  • strncpy(s.name, &names[i], strlen(names[i]));? Commented Apr 10, 2018 at 16:48
  • Take a look at this answer: stackoverflow.com/questions/2641473/… Commented Apr 10, 2018 at 16:48
  • s is type........ Commented Apr 10, 2018 at 16:49
  • Sorry, there's a few errors in the code, I just wanted to put down the general idea of what I was trying to do. It isn't literally what I pasted Commented Apr 10, 2018 at 16:50
  • Array has allocated memory. You can't point it to another location. Commented Apr 10, 2018 at 18:45

1 Answer 1

1

I guess you're trying to split the array containing names into two structs.

To do that based on what you have done :

Include <string.h>

Then change :

for (int i = 0; i < 2; i++) {
        s tmp;
        s.name = names + i;
    }

To :

for (int i = 0; i < 2; i++) {
       strcpy(stru[i].name, names[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

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.