Home > Blockchain >  why the chart in C can't display my words?
why the chart in C can't display my words?

Time:10-04

#include <stdio.h>
int main(void)
{
char firstname = "Lux";
char lastname = "Ren";
printf("My name is %s %s\n", firstname, lastname);
printf("My first name is %s \n", firstname);
printf("My last name is %s\n", lastname);
printf("My full name is %s %s\n", firstname,lastname);
return 0;
}

i try to print the name but after i run the system shows me like thatenter image description here me

CodePudding user response:

Like a couple of people already mentioned, to declare a string in C you need to initialize it as a char[] rather than only char or as a char* like @kaylum mentioned since arrays and pointers are equivalent in C.

CodePudding user response:

The syntax for a character is as follows:

char variableName = 'any character';

You can only initialise or take as input a single character when you have declared the variable as char. The format specifier for char is %c.

To initialize a string in c, you have to declare the variable with square braces, like this:

char firstName [] = "Lux";

The compiler takes care of the buffer space when you initialise the variable while declaring it, but if you were to take it as input, you would have to take care of the it yourself so you don't get a buffer overflow. The format specifier for a string is %s. And if you use scanf for taking a string array as input, do not use the & sign before the variable name as an array itself points to a memory address and fills scanf's requirement beforehand.

  • Related