-1

hello Structure element (string )is unable to assign if it is not assign during object creation as below code why ?my code is below please help me to understand

 struct st
 {
   int i;
   char ch[10];
   char *ch1;
 };

  int main()
{
    struct st var2={"hello"};//this good

    struct st var;

    var.ch="hello" ; //this bad why?

    //then
    var.i=9;//is good why?

    var.ch1="hello"; //good why?
}
leuage
  • 566
  • 3
  • 17
  • possible duplicate of [How do I use arrays in C++?](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c) – ApproachingDarknessFish Nov 04 '14 at 16:03
  • Use `strcpy` for it to work. Arrays can be 'initialized' ,but not 'assigned' – Spikatrix Nov 04 '14 at 16:04
  • @ValekHalfHeart Why did you mark a c++ question as a duplicate, when this is clearly c? – 2501 Nov 04 '14 at 16:05
  • @2501 AFAIK there's no canonical c question about array usage, and since VLA's aren't involved the same rules apply. I was just looking for a question that explained that arrays are not assignable. In retrospect, this would've been a better dupe: http://stackoverflow.com/q/4978056/1530508 – ApproachingDarknessFish Nov 04 '14 at 16:17

2 Answers2

0

This link will help: Char array declaration and initialization in C

There is a difference between assignment and initialization.You are doing array assignment which is not allowed and also didn't your compiler throw below error:

warning: initialization makes integer from pointer without a cast

for

struct st var2={"hello"};
Community
  • 1
  • 1
Gopi
  • 19,784
  • 4
  • 24
  • 36
0

struct st var2={"hello"};//this good

No, it is not good.:) You are trying to initialize integer varaiable i with pointer to the first character of string literal "Hello".

var.ch="hello" ; //this bad why?

This is indeed bad because arrays have no assignment operator. You have to use standard function strcpy declared in header <string.h> that to copy the string literal in data member ch. For example

strcpy( var.ch, "hello" );
var.i=9;//is good why?

var.ch1="hello"; //good why?

These are good because built-in types (fundamental types) including pointers have assignment operators.

In the last statement the array that corresponds to string literal "hello" is converted to a pointer to its first element that is to pointer to character 'h' and this pointer is assigned to ch1.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335