chanzerre
chanzerre

Reputation: 2429

Declaration and initialization of strings

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.

Upvotes: 2

Views: 116

Answers (3)

Yxuer
Yxuer

Reputation: 44

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.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477308

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.

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 225022

  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.

Upvotes: 1

Related Questions