0

When you try and assign character arrays after initializing them you must use a function like strcpy.

#include<stdio.h>

void main()
{
    struct emp
    {
        char name[25];
        int age;
        float bs;
    };
    struct emp e;
    e.name = "Steven";
    e.age = 25;
    printf("%s %d\n", e.name, e.age);
}

This code would only work if I made the following changes

#include<stdio.h>

void main()
{
    struct emp
    {
        char name[25];
        int age;
        float bs;
    };
    struct emp e;
    strcpy(e.name,  "Steven");
    e.age = 25;
    printf("%s %d\n", e.name, e.age);
}

However, if we use a pointer instead of an array we can assign the string after initializing.

#include<stdio.h>

void main()
{
    struct emp
    {
        char *name;
        int age;
        float bs;
    };
    struct emp e;
    e.name = "Steven";
    e.age = 25;
    printf("%s %d\n", e.name, e.age);
}

Why does this work but not the first code if both a pointer and an array point to a memory location?

Arthur Green
  • 136
  • 1
  • 10
  • 2
    Because - contrary to what people who do not understand c will tell you - arrays are not pointers, nor are pointers arrays. – EOF Nov 30 '18 at 23:53
  • @EOF Pointer arrays are arrays of pointers, though. \*scnr\* – Swordfish Nov 30 '18 at 23:56
  • I feel that the terminology is incorrect. Initialization of a variable (array or otherwise) happens at declaration. At any other point while we call it initialization is simply manipulating the variable. – fdk1342 Nov 30 '18 at 23:59
  • 1
    C doesn't have a string type; you have to use functions like strcpy() and strcmp() to do string-like things. So `e.age = 25` is fine; but you'll need `strcpy(e.name, "Steven")` to do that assignment. Compile-time initialization is a little easier if you can do that. – Lee Daniel Crocker Dec 01 '18 at 00:12

1 Answers1

1

the first does not work because assigning a pointer to an array is meaningless. However, the second works because it is assigning a pointer to a pointer

user3629249
  • 16,402
  • 1
  • 16
  • 17
  • Assigning a pointer to an array does have meaning (as in pointer on the left hand side of an assignment, name of array on the right) but it doesn't copy the contents of the array. The reverse is not possible. – Peter Dec 01 '18 at 00:09
  • @Peter Maybe you want to think about that statement once more. – Swordfish Dec 01 '18 at 00:10