1

I have a struct that contains a string value:

struct Demo { char str[256]; }; 

When I try to initialize the struct, like here:

char str[256] = "asdasdasd"; struct Demo demo = {str}; // print to check what's in there puts(demo.str); 

I get a warning:

warning: initialization of ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion] 8 | struct Demo demo = {str}; | ^~~ .\Untitled-1.c:8:29: note: (near initialization for ‘demo.str[0]’) 

Why is demo.str[0], a character, getting initialized when the struct needs to contain a string?

1
  • 1
    It's just not possible to initialize an array using another array. Initialize the rest of the structure, and then copy the string (using strcpy). Commented Nov 6, 2023 at 7:42

1 Answer 1

1

In C, when you use an array name in an expression, it "decays" into a pointer to its first element, so you can't initialize an array using another array directly. You can use the strcpy function to copy characters from the str array to demo.str:

#include <stdio.h> #include <string.h> struct Demo { char str[256]; }; int main() { char str[256] = "asdasdasd"; struct Demo demo; strcpy(demo.str, str); puts(demo.str); return 0; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Another option would be to initialize it directly with a string literal, i.e. struct Demo demo = {"asdasdasd"};.