Search code examples
cc-strings

"initialization of ‘char’ from ‘char *’ makes integer from pointer without a cast" when initializing a struct with string in C


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?


Solution

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