defining a string value for structure variable

11,955

Solution 1

You can only initialize array like that at the time of declaration only, else you need to use

strcpy(variable.array,"hello");

you can't even do like that with a simple char array

char a[10];

a="hello";

the complier will tell :

incompatible types when assigning to type ‘char[10]’ from type ‘char *’

because "hello" is a string literal that is being held by a pointer which can't be assigned like this to an array.

Solution 2

In C the term "hello" means "a pointer to a string that has the chars 'hello\0' in it". So when you assign array="hello" in the first case you are assigning the pointer to the string into a pointer variable. Which is right.

In the second case you try to assign a pointer to an array which is wrong! you can't assign value to an array.

Solution 3

It raises an error because an array of char and a pointer to char are different things.

An array is not a pointer. A pointer is not an array. Sometimes a pointer might point to an array. But even when a pointer points to an array, it's not an array.

Your compiler gives an address to variable.array at compile time. It also gives an address to the string literal "hello". They're not the same address. The string literal and the array (or "the buffer") are in different places; logically, the string has to be copied into the buffer.

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

struct name {
    char array[10];
}variable;

int main( void ){

    strcpy(variable.array, "hello");
    printf( "%s\n", variable.array );
    return 0;

}

You might find the C FAQ useful.

Share:
11,955
Nagaraj Tantri
Author by

Nagaraj Tantri

YOLO = "You Only Live Once" while len(YOLO) &gt; 0: print "ENJOY_LIFE"

Updated on June 14, 2022

Comments

  • Nagaraj Tantri
    Nagaraj Tantri about 2 years

    I was just going through certain interview questions. Got this structure related issue, I m not understanding what is happening wit the output, Please if some could explain the reason.

    When is use a character pointer in the structure like

    #include <stdio.h>
    
    struct name {
        char *array;
    }variable;
    
    int main( int argc, char * argv[] ){
    
        variable.array="hello";
        printf( "%s\n", variable.array );
    }
    

    The output is hello printed, but when change the structure variable to

    struct name {
        char array[10];
    }variable;
    

    The compiler throws an error "incompatible types in assignment" at

    variable.array="hello";
    

    I am really confused as to where i am missing the point. Why does it show the error like assignment problem?? Please correct me Thank you