How to use a variable twice in C?

Viewed 146

I am quite new to C and i am trying to use a variable twice in one line:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int myAge = 10;
    char PL = "C";
    printf("I am Rydex (not my real name) and i am %d years old. This was made using %s", myAge, PL);
}

But, when i run it, I get:

I am Rydex (not my real name) and i am 10 years old. This was made using (null)

Instead of the value in the variable "PL" i get "(null)". Can someone please help me?

5 Answers

PL is a string, not a char. You need to change the declaration to:

char* PL = "C";

The double-quoted delimiter is for a string constant, which has a span of characters terminated with a null character \0. A single quote delimiter is to define a single character constant. Here's a good write-up

You should use

char * PL = "C";

To declare PL as a pointer. You probably also want \n at the end of your format string.

I'm surprised your compiler didn't complain that you weren't declaring a pointer. Mine did. It didn't like the string "C" (which is 2 bytes) being declared as a single character (which is equivalent to a single byte integer)

test.c: In function ‘main’:
test.c:7:15: warning: initialization of ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversio ]
     char PL = "C";

Also, when you try to use %s in printf function, it expects type char* – a pointer to char. Try using %c instead with type char.

There are two ways to fix this:

  1. Change the declaration of PL to
    char *PL = "C";
    or
    char PL[] = "C";
    The %s format specifier expects its corresponding to have type char * - in other words, it expects PL to be the address of the first character of a string. The string "C" is actually an array of char containing the sequence {'C', 0}. Under most circumstances, an expression of array type is converted, or "decays", to a pointer type and the value of the expression is the address of the first element of the array.
  2. Change the declaration of PL to
    int PL = 'C'; // single quotes, not double
    and use %c instead of %s in the printf call:
    printf("I am Rydex (not my real name) and i am %d years old. This was made using %c", myAge, PL);
    'C' is a character constant, not a string. The %c format specifier expects its corresponding argument to have type int. In this case, PL stores the character code for 'C' (67 in ASCII and UTF-8).

Use char *PL = "C" instead of char PL = "C". Notice the asterisk. That is called a pointer, but that's a topic for another time.

Related