-1

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);
3
  • 1
    Use strncpy(). Commented Aug 31, 2021 at 12:19
  • 2
    Your program shouldn't even compile, much less run and give you output. You can't assign to arrays, only copy to them. Commented Aug 31, 2021 at 12:20
  • 2
    @GhasemRamezani Which needs to be handled with care, as there's a corner case where it will not add the string terminator. A safer variant might be snprintf. Commented Aug 31, 2021 at 12:20

1 Answer 1

3

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!
Sign up to request clarification or add additional context in comments.

2 Comments

Addition: If floppy380 wants to keep the p1.myArray = "HELLO!"; assignment, then declaring myArray as a char* also works. The pointer will then point to the string literal.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.