top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between string and character arrays ?

0 votes
336 views
What is the difference between string and character arrays ?
posted Jul 23, 2014 by Chahat Sharma

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
  1. A character array is a collection of characters.
    char a[5] = {'a','b','c','d','e'};
    To print this array you need to run a loop 5 times and print it character by character using %c.

  2. A string is also a collection of characters BUT ending with a NULL (\0) character.
    char a[8] = "example";
    To print this string, we can directly use "%s" and print the whole array in 1 shot since "%s" continuously prints until it hits a NULL character.
    You can observe that the number of characters in this string are 7 but the size of the array is 8 bytes. 1 extra byte to store the NULL character (\n).

answer Jul 24, 2014 by Ankush Surelia
Similar Questions
+3 votes
#include<stdio.h>
#include<string.h>

int main()
{
    char ptr[]= {'a','b','c','0','e'};
    char str[]= "abc0e";
    printf("\nptr = %s\t len = %d\n",ptr, strlen(ptr));
    printf("\nstr = %s\t len = %d\n",str, strlen(str));
    return 0;
}

Output : ptr = abc0e len = 6
str = abc0e len = 5

Why the length for ptr is 6 ? Can someone please explain it ?

0 votes
...