How to print a char array in C through printf?
Solution 1
The code posted is incorrect: a_static
and b_static
should be defined as arrays.
There are two ways to correct the code:
you can add null terminators to make these arrays proper C strings:
#include <stdio.h> int main(void) { char a_static[] = { 'q', 'w', 'e', 'r', '\0' }; char b_static[] = { 'a', 's', 'd', 'f', '\0' }; printf("value of a_static: %s\n", a_static); printf("value of b_static: %s\n", b_static); return 0; }
Alternately,
printf
can print the contents of an array that is not null terminated using the precision field:#include <stdio.h> int main(void) { char a_static[] = { 'q', 'w', 'e', 'r' }; char b_static[] = { 'a', 's', 'd', 'f' }; printf("value of a_static: %.4s\n", a_static); printf("value of b_static: %.*s\n", (int)sizeof(b_static), b_static); return 0; }
The precision given after the
.
specifies the maximum number of characters to output from the string. It can be given as a decimal number or as*
and provided as anint
argument before thechar
pointer.
Solution 2
This results in segmentation fault. ? because of the below statement
char a_static = {'q', 'w', 'e', 'r'};
a_static
should be char array
to hold multiple characters. make it like
char a_static[] = {'q', 'w', 'e', 'r','\0'}; /* add null terminator at end of array */
Similarly for b_static
char b_static[] = {'a', 's', 'd', 'f','\0'};
Solution 3
You need to use array instead of declaring
a_static
b_static
as variables
So it look like this:
int main()
{
char a_static[] = {'q', 'w', 'e', 'r','\0'};
char b_static[] = {'a', 's', 'd', 'f','\0'};
printf("a_static=%s,b_static=%s",a_static,b_static);
return 0;
}
Related videos on Youtube
Aquarius_Girl
Arts and Crafts.stackexchange.com is in public beta now. Join us!
Updated on May 14, 2020Comments
-
Aquarius_Girl about 4 years
This results in segmentation fault. What needs to be corrected?
int main(void) { char a_static = {'q', 'w', 'e', 'r'}; char b_static = {'a', 's', 'd', 'f'}; printf("\n value of a_static: %s", a_static); printf("\n value of b_static: %s\n", b_static); }
-
Jabari Dash about 6 years
char *a_static
use a pointer -
Martin James about 6 years
-
Cœur about 6 yearsPossible duplicate of Definitive List of Common Reasons for Segmentation Faults
-
-
Aquarius_Girl about 6 yearsAh! Thanks for the fault.
-
Anirudh about 6 yearsYou should also add the '\0' characters in your char array to prevent overflow.
-
too honest for this site about 6 yearsThat's problematic and partially wrong in various places. For a start: pointers are never a replacement for arrays. If one feels like answering questions witrh broken code and lack of fundamentals like that, they at least should get it very correct so OP will not need to buy a textbook to learn the language properly which would be the correct way.