Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a char array in C through printf? [closed]

Tags:

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); } 
like image 600
Aquarius_Girl Avatar asked May 13 '18 02:05

Aquarius_Girl


People also ask

How do I print a char?

You want to use %s , which is for strings (char*). %c is for single characters (char). An asterisk * after a type makes it a pointer to type.

How do you store characters in an array?

To store the words, a 2-D char array is required. In this 2-D array, each row will contain a word each. Hence the rows will denote the index number of the words and the column number will denote the particular character in that word.


2 Answers

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 an int argument before the char pointer.

like image 123
chqrlie Avatar answered Sep 20 '22 22:09

chqrlie


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'}; 
like image 40
Achal Avatar answered Sep 20 '22 22:09

Achal