3

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?

3
  • char name[10] is equal to char* name but with different allocation. Commented Aug 8, 2012 at 12:25
  • When you declare an array like this, char name[10];, you get an array with ten elements, numbered 0 to 9 inclusive. So a.name[10] is outside the bounds of the array. It's not a good idea to try to assign it a value. Commented Aug 8, 2012 at 12:27
  • You need to learn about arrays before you learn about strings. Commented Aug 8, 2012 at 12:30

4 Answers 4

7

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!)

Sign up to request clarification or add additional context in comments.

3 Comments

Shouldn't name be a const char* in the second case? :)
@KirilKirov fixed, and added one more possibility. :)
Looks better now :) +1 for your competitive answer :)
6

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" );

Comments

3

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.

Comments

0

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};

1 Comment

Although an initializer resembles an assignment (and thus the OP's confusion), it isn't one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.