-1

This is a very basic question, it has been asked alot, but all of the examples I have looked at have been slightly different

#include<stdio.h>

int main() {

    char title[] = "HELLO!";
    title[1] = "F";

    printf("%s", title);

}

Why does this cause the following error -

jdoodle.c:6:14: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
     title[1] = "F";

Cheers

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
eZ_Harry
  • 816
  • 9
  • 25

1 Answers1

2

"F" is a string literal. It has type char[2] (that is it is a character array containing a string) and is presented in memory like

char unnamed_literal[] = { 'F', '\0' };

From the C Standard (6.4.5 String literals)

6 In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.78) The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence...

For example try to execute this statement

printf( "%zu\n", sizeof( "F" ) );

In this expression statement

title[1] = "F";

the left operand has type char while the right operand that has the type char[2] is implicitly converted to pointer to its first element that is it has type char *.

From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)

3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

So in this statement

jdoodle.c:6:14: warning: assignment makes integer from pointer without a cast

that is there is an attempt to assign the address of the first character of the string literal to a character that does not make sense.

It is evident that you mean assigning the character constant 'F' to the object title[1] of the type char.

That is you mean the following statement

title[1] = 'F';

You could use the string literal but you need its first character instead of its address. You could write for example

title[1] = "F"[0];

or

title[1] = *"F";

or even like

title[1] = 0["F"];

But of course it is better and simpler just to use the character constant instead of the string literal

title[1] = 'F';
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335