1

The question is very simple but I'm confused that why the struct is behaving like this as all of its members are by default public, have a look at following code

struct Student
{
   char name[20];
}
int main()
{
   Student s;
   s.name="ahmed";
}

This code gives an error that name should be a modifiable lvalue.

But if I assign value in a loop char by char, then it works fine like this

s.name[0]='a';//works fine
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Ahmed
  • 2,176
  • 5
  • 26
  • 40

5 Answers5

3

Arrays in C are non-assignable and non-copy-initializable and in C++ this behavior was inherited. On the right-hand side arrays decay to pointers but in your case your copy-initialization is just not allowed.

If you try this:

{
   char name[20];
   name="ahmed";
}

you're actually copy-initializing the array - and that's disallowed.

The only exception is initializing them with a string literal

 char c[] = "abc";

In your case you should rather use a function called strcpy to accomplish that:

{
   char name[20];
   strcpy(&name[0],"ahmed"); // Obviously make sure that there's enough space
}
Marco A.
  • 43,032
  • 26
  • 132
  • 246
2

It's worth noting that you can also use strings to accomplish this task:

#include<iostream>
#include<string>
using namespace std;

struct Student{
   string name;
};

int main()
{
   Student s;
   s.name = "ahmed";
}
  • of course i know that i can do it with string. I just wanted to know why char[] behave like this – Ahmed Feb 08 '14 at 10:56
2

Structure is not a problem in your case. Arrays in C are not assignable.

Instead of s.name = "ahmed" , use strcpy(s.name,"ahmed")

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
RahulKT
  • 171
  • 4
1

name is an array, and you can't assign to an array name. Instead, you should use std::strcpy in cstring to copy the contents of the C-style string.

std::strcpy(s.name, "ahmed");

Note that the problem has nothing to do with the fact that name is part of a struct. You would have the same problem with a native char array.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
0

You must use:

struct Student
{
   char *name;
};

int main()
{
   Student s;
   s.name = "ahmed";
   return 0;
}
mb84
  • 683
  • 1
  • 4
  • 13
  • Isn't it equivalent to my code? name is a char pointer in both cases – Ahmed Feb 08 '14 at 10:57
  • 1
    Not really. `name` of `char name[20]` is only on the right side of an assignment a `char *` type. On the left side it isn't allowed to appear, *except* for initialization (first-time). – mb84 Feb 08 '14 at 11:00