user7425291
user7425291

Reputation:

Why do I get: "error: assignment to expression with array type"

#include <stdio.h>

int main(void) {
    int arr[10];
    arr = "Hello";
    printf("%s",arr);
    return 0;
}

The above code shows compiler error:

t.c: In function ‘main’:
t.c:5:9: error: assignment to expression with array type
     arr = "Hello";
         ^
t.c:6:12: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("%s",arr);
            ^

Whereas the below code works fine.

#include <stdio.h>

int main(void) {
    char arr[10] = "Hello";
    printf("%s",arr);
    return 0;
}

Both look identical to me. What am I missing here?

Upvotes: 1

Views: 67297

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

They are not identical.

First of all, it makes zero sense to initialize an int array with a string literal, and in worst case, it may invoke undefined behavior, as pointer to integer conversion and the validity of the converted result thereafter is highly platform-specific behaviour. In this regard, both the snippets are invalid.

Then, correcting the data type, considering the char array is used,

  • In the first case,

      arr = "Hello";
    

is an assignment, which is not allowed with an array type as LHS of assignment.

  • OTOH,

      char arr[10] = "Hello";
    

is an initialization statement, which is perfectly valid statement.

Upvotes: 6

akitsme
akitsme

Reputation: 45

Don't know how your second code is working (its not working in my case PLEASE TELL ME WHAT CAN BE THE REASON) it is saying: array of inappropriate type (int) initialized with string constant

Since you can't just assign a whole string to a integer variable. but you can assign a single character to a int variable like: int a[5]={'a','b','c','d','d'}

Upvotes: -3

Related Questions