wifi
wifi

Reputation: 1

What actually happening when I try assign string to char in C?

#include <stdio.h>

int main() {
    char a;
    a = "v";
    printf("%c", a);
    return 0;
}

When I try this, 'd' was printed with warning: assignment makes integer from pointer without a cast [-Wint-conversion]

What was happening when I run this code?

I think "v" means actually ['v', '\0'] make this, and I want know about what make "v" to 'd' in detail.

Upvotes: -1

Views: 106

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409136

You have to remember (or learn) that all literal strings in C are really arrays of characters (including the terminating null-character).

If we then create an actual array in the code itself, and take a look at what it will do:

char s[2] = "v";  // s[0] == 'v', s[1] == '\0'

char a;
a = s;

What happens here is that s will decay to a pointer to its first element, and you assign that pointer to the variable a:

char *temp = &s[0];
a = temp;  // No dereference of the pointer, it's the pointer itself that is assigned from

Unfortunately a whole pointer can seldom fit inside a single char variable (I don't know of any such system), so the compiler will store only enough bits of the pointer value (typically 8 bits, one byte) inside the variable a.

What the actual value of a will be after this is indeterminate (I think, could be undefined, or implementation defined). It also depends on if char is signed or unsigned (which is implementation defined, i.e. up to the compiler).

Upvotes: 2

0___________
0___________

Reputation: 67476

I think "v" means actually ['v', '\0'] make this, and I want know about what make "v" to 'd' in detail.

"v" is a string literal which is a char array of two char elements 'v' and '\0'.

What actually happening when I try assign string to char in C?

When you assign a string literal to the char variable:

  1. the string literal decays to the address of its first element.
  2. this address is being converted to the char integer (char is an integer type) type. This value us assigned to the a variable.

It makes no sense and if char is signed it will invoke Undefined Behaviour. The value stored in the a does not have any usable sense.

Upvotes: 0

Related Questions