2

Why doesn't this work?

#include<stdio.h>
int main()
{
char ch[50];
ch[50]="manipulation";
puts(ch);
}

and why does this work?

#include<stdio.h>
int main()
{
char ch[50]="manipulation";
puts(ch);
}

By "it works" I mean i get the output i want, that is, printing of "manipulation"(without quotes) as standard output.

chanzerre
  • 2,409
  • 5
  • 20
  • 28
  • read [Difference between `char *str` and `char str[]` and how both stores in memory?](http://stackoverflow.com/questions/15177420/what-does-sizeofarray-return/15177499#15177499) – Grijesh Chauhan Aug 31 '13 at 06:12

3 Answers3

1
  1. ch[50] = "manipulation" isn't valid syntax. Closer would be ch = "manipulation", but arrays aren't modifiable lvalues, so you can't assign to them. Use strcpy(3), or declare ch as a pointer instead:

    strcpy(ch, "manipulation");
    

    or

    char *ch;
    ch = "manipulation";
    
  2. Your second example is an initialization, not an assignment expression. This form creates an array ch and copies the provided string literal to initialize it.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • No, in a declaration it means "initialization". It has to be different from an expression so you can use it at global scope or to initialize objects with static storage duration. – Carl Norum Aug 30 '13 at 23:22
1

You cannot assign naked C arrays, that's why. The second case isn't assignment at all, but initialization.

If you do want to assign arrays, you can achieve this by wrapping them in a struct:

struct Char50 { char data[50]; };

struct Char50 x;
struct Char50 y = { "abcde" };
x = y;
puts(x.data);

The more idiomatic way of handling strings is strcpy, though, e.g. strcpy(ch, "abcde");, though you have to be careful about the destination buffer size.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

It doesn't work because with the syntax:

ch[50]="manipulation";

You're assigning the string "manipulation" to the 50th element of ch. That's not possible because the array is composed of idividual characters, and you're assigning a string to a individual char. Also, ch has elements from 0 to 49, and there's not a 50th element.

If something's wrong with my explanation, please tell me. And sorry for my bad english.

Yxuer
  • 44
  • 7