'how to I copy structure char variable into another char array [duplicate]

struct student
{
    char name[50];
    int rollno;
    float marks;
};
int main()
{
    char nam[50];
    int i = 0, n=5;
    struct student s1[n];
    for(i=0;i<n;i++)
    {
       nam[i] = s1[i].name;
     }
}

In given code, I am unable to copy s1[i].name in nam[i], I tried all the copy function but it's giving me error every time.



Solution 1:[1]

This ...

       nam[i] = s1[i].name;

... does not make sense because name[i] is one char, whereas s1[i].name is an array of 50 chars. Moreover, your loop is over the number of elements of s1 (5), which is much less than the number of elements of nam or s1[i].name.

Supposing that you really do want s1 to be an array of struct student as opposed to just one struct, you probably want to use strcpy(). However, you might want or need to use memcpy() (or an element by element copy loop) depending on the nature of the contents of s1 and its elements and any artificial requirements on the exercise.

The strcpy() variation would look like this:

       strcpy(nam, s1[i].name);
       // do something with nam ...

That depends on the source array to contain a null-terminated string, which is not guaranteed to be the case in the demo program, which never puts any data in s1 or its elements.

Solution 2:[2]

Use strcpy() I have tried and it's working

Solution 3:[3]

Lots of little things working against you in this code, eg the following...

int i = 0, n=5;
struct student s1[n];

...creates a variable length array of struct student, preventing an initializer from being a viable path. But if for the sake of illustration you can live with a non-VLA version, then try this:

//Use a hard-coded to `5`,  to create an array of 5 struct student, initialized as shown: 
struct student s1[5] = {{"name1"1, 1.0},("name2",2,2.0},{"name3",3,3.0},{"name4",4,4.0},{"name5",5,5.0}}; 

Next, your current code: char nam[50]; creates a single uninitialized char array, sufficient for containing only 1 string with up to 49 characters, with a terminating \0. If you can, create it like this. (for the sake of learning to copy strings in a loop.)

char nam[5][50] = {{0}};//created 5 elements of null terminated char array elements, 

Then you can do this in your loop:

for(i=0;i<n;i++)
{
   strcpy(nam[i], s1[i]name);
}

By now (from comments and answers) you should already know that strings cannot be copied using the = operator like integers or floating numbers. String functions such as strcpy(), or sprintf() can be used to populate strings.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John Bollinger
Solution 2 Peter Csala
Solution 3