overexchange overexchange - 1 month ago 7
C Question

How to display character array?

In the below code,

#include<stdio.h>
int main(){
char string[] = {1, 2, 3};
char* my_pointer = string;
printf("%c", *my_pointer);
}


Am expecting the ASCII character
'1'
to be displayed on screen.

ASCII character
'1'
is
49
with binary representation as
00110001

Answer

You need to give it characters when initializing:

char string[] = {'1', '2', '3', '\0'};

or you can initialize using a string

char string[] = "123";

When you use numbers like

  char string[] = {1, 2, 3};

it will print the ASCII character corresponding to the number 1 (which is most likely not generating any output).

If you want to initialize using numbers, you must do:

  char string[] = {49, 50, 51};
Comments