Showing posts from October, 2016

Character arrays and Strings in C

It is a general misconception that both character arrays and strings are one and the same. But, THEY ARE NOT THE SAME. If you already know the difference between them, then I hope this post will add a little more to what you already know.

What are character arrays and strings?

let's first see what they have in common. A character array and string are both sequence of characters i.e, they store the base address of multiple characters  in sequence and these characters can be accessed using index value.

Here is what happens when you initialize a character array:
//character array:char ch_arr[3]="abc";/* DESCRIPTION:*here,*ch_arr[0] stores 'a'*ch_arr[1] stores 'b'*ch_arr[2] stores 'c'*/
Here's what happens when you initialise a string:
//string:char str[]="abc";/* DESCRIPTION:*here,*str[0] stores 'a'*str[1] stores 'b'*str[2] stores 'c'* additionally str[3] stores '\0'(nul character)*/
From the above two bloc…

Issues with using scanf() to scan characters in loops in C

I've been a member of the question and answer site Stack Overflow for nearly a year now and there is one question that's always asked by beginners  in C language regarding scanning characters in a loop. Generally they would have a program like this:

#include "stdlio.h" int main(void) { char again = 'y'; //declaration and initialisation of a `char` variable //declarations of other variables... //program.... //THE LOOP while (again == 'y') { //looping statement..... printf("want again? y/n : "); //THE PROBLEM scanf("%c", &again); //scanning the character } //rest of the program.... return 0; }
and the question is why does the loop run only once even though they have entered input as `y` when prompted the message `want again?` while running the executable file. If you've done…