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); }
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.
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.
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.
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'};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With