mko
mko

Reputation: 22114

String assignment in C

I'm new to C. The string assignment in the following code works:

#include<stdio.h>
int main(void){
  char str[] = "string";
  printf("%s\n",str);
}

But doesn't work in the following,even I give the index number to the name[]:

#include <stdio.h>
int main(void){
  struct student {
    char name[10];
    int  salary;
  };
  struct student a;
  a.name[10] = "Markson";
  a.salary = 100;
  printf("the name is %s\n",a.name);
  return 0;
}

Why does this happen?

Upvotes: 3

Views: 3810

Answers (4)

user529758
user529758

Reputation:

You can't assign to an array. Two solutions: either copy the string:

strcpy(a.name, "Markson");

or use a const char pointer instead of an array and then you can simply assign it:

struct {
    const char *name;
    /* etc. */
};

a.name = "Markson";

Or use a non-const char pointer if you wish to modify the contents of "name" later:

struct {
    char *name;
}

a.name = strdup("Markson");

(Don't forget to free the memory allocated by strdup() in this latter case!)

Upvotes: 7

AndersK
AndersK

Reputation: 36102

because in one case you assigning it in a declaration and in the other case you are not. If you want to do the equivalent write:

struct student a = {"Markson", 0};

Upvotes: 0

Michael
Michael

Reputation: 58497

char str[] = "string"; is a declaration, in which you're allowed to give the string an initial value.

name[10] identifies a single char within the string, so you can assign a single char to it, but not a string.

There's no simple assignment for C-style strings outside of the declaration. You need to use strcpy for that.

Upvotes: 3

Kiril Kirov
Kiril Kirov

Reputation: 38173

You cannot do this

a.name[10] = "Markson";

You need to strcpy the string "Markson" to a.name.

strcpy declaration:

char * strcpy ( char * destination, const char * source );

So, you need

strcpy( a.name, "Markson" );

Upvotes: 6

Related Questions