dn70a
dn70a

Reputation: 83

Question on storing a string inside a struct member in c

Can someone explain

Why does the below code work for saving a string in a struct member

struct prefix {
    char aString[70];
};

struct prefix data={
  .aString = "d08430c90b467422ae9bf7f8ecf8a77682f92764efe53e0ebe26d4ffb6fb96bf"
 };

while the code below does not?

struct prefix {
    char aString[70];
};

struct prefix data;

data.aString = "d08430c90b467422ae9bf7f8ecf8a77682f92764efe53e0ebe26d4ffb6fb96bf"; 
              //Array type 'char [70]' is not assignable

Upvotes: 0

Views: 68

Answers (2)

Luis Colorado
Luis Colorado

Reputation: 12708

the expression

data.aString = "d08430c90b467422ae9bf7f8ecf8a77682f92764efe53e0ebe26d4ffb6fb96bf";

(a string literal) is just a pointer, pointing to some initialized data segment, filled with the characters you have written between double quotes, plus a null character at the end.... it's the address of that array of characters what is passed on the assignment, and that requires a pointer type (and not an array, which is what you have declared)

Use

    strcpy(data.aString, "d08430c90b467422ae9bf7f8ecf8a77682f92764efe53e0ebe26d4ffb6fb96bf");

to copy the fixed string literal into the memory occupied by the array. Or better, to protect you in case you use a string that doesn't fit in the array size:

    strncpy(data.aString, "d08430c90b467422ae9bf7f8ecf8a77682f92764efe53e0ebe26d4ffb6fb96bf", sizeof data.aString);

Upvotes: 0

pmg
pmg

Reputation: 108986

initialization: create an object and specify its value in one instruction;
assignment: change the value of a pre-existing object

struct prefix data = { ... }; // initialization;
struct prefix data; // not initialized now, cannot ever initialize it later, only assign

Upvotes: 2

Related Questions