Cannot output the C struct char array member

326 Views Asked by At

I'm learning how to use structures in C. But in the following code I couldn't print myArray "HELLO!" which is declared as a char array:

#include <stdio.h>

struct myStruct
{
    int myInt;    
    float myFloat;
    char myArray[40];
};

int main()
{
    struct myStruct p1;
    
    p1.myInt = 80;
    p1.myFloat = 3.14;
    printf("Integer: %d\n", p1.myInt);
    printf("Float: %f\n", p1.myFloat);
    
    p1.myArray = "HELLO!";
    printf("Array: %s\n", p1.myArray);

    return 0;
}

What is wrong in the above syntax that I don't get "HELLO!" as an output? Something wrong here:

p1.myArray = "HELLO!";
printf("Array: %s\n", p1.myArray);
1

There are 1 best solutions below

2
On

Arrays are non-modifiable lvalues. So this attempt to assign a pointer (the string literal is implicitly converted to a pointer to its first element) to an array designator

p1.myArray = "HELLO!";

will not compile.

Either use the standard string function strcpy as for example

#include <string.h>

//...

strcpy( p1.myArray, "HELLO!" ); 

Or you could initialize the data member initially when the object of the structure type is defined as for example

struct myStruct p1 = { .myInt = 80, .myFloat = 3.14, .myArray = "HELLO!" };

or

struct myStruct p1 = { .myInt = 80, .myFloat = 3.14, .myArray = { "HELLO!" } };

or

struct myStruct p1 = { 80, 3.14, "HELLO!" };

or

struct myStruct p1 = { 80, 3.14, { "HELLO!" } };

Here is a demonstrative program.

#include <stdio.h>
#include <string.h>

struct myStruct
{
    int myInt;    
    float myFloat;
    char myArray[40];
};

int main( void )
{
    struct myStruct p1 = { .myInt = 80, .myFloat = 3.14, .myArray = { "HELLO!" } };

    printf("Integer: %d\n", p1.myInt);
    printf("Float: %f\n", p1.myFloat);
    printf("Array: %s\n", p1.myArray);

    strcpy( p1.myArray, "BYE!" );
    
    printf("\nArray: %s\n", p1.myArray);

    return 0;
}

The program output is

Integer: 80
Float: 3.140000
Array: HELLO!

Array: BYE!