in Programming in C
1,950 views
0 votes
0 votes
Prog 1 : 
#include<stdio.h>
#include<string.h>
void foo(char *);
int main()
{
    char a[100] = {0};
    printf("%lu %lu",sizeof(a),strlen(a));
    return 0;
}

Prog 2

#include<stdio.h>
#include<string.h>
int main()
{
    char string[] = "Hello";
    printf("%lu %lu",sizeof(string),strlen(string));
    return 0;
}
in Programming in C
2.0k views

2 Answers

3 votes
3 votes
Best answer

Few points before solving:

1) Difference among  0 , '0', '\0', nul, NULL : In C program, we use only ASCII chars to write our program.Each ASCII char has name,notation and its corresponding ASCII value. e.g. nul(don't confused with NULL) is ASCII name for null byte which is represented as '\0' and its ASCII value is integer 0. NULL is somewhat similar to '\0' in the sense its value is 0 but it is meant for using in pointer initialisation and it refers to "nothing" or memory location zero.And '0' is char which has ASCII value 48,"1" has ASCII value 49 & so on.

2) "Sizeof" operator gives memory size occupied by given datatype in byte.In also counts  nul character size in case of string representation. "strlen" function returns length of string but it doesn't include count of nul character.

3)char a[100] = {0}; or char a[100] = {'\0'}; or char a[100] = {0};  char a[100] = {NULL};(some compiler gives warning) all are equivalent and used for initialising all elements of array to default value i.e here default value of char type i.e nul('\0').

Output of prog 1:  

         char a[100] = {0}   is equivalent to  "000000..........upto 100times". It takes 100 chars space i.e 100 byte in memory.So sizeof(a) = 100  & since it represents 'nul'  so strlen(a) = 0.  Hence output is  100 0.

Output of prog 2:  

         char string[] = "hello"; is internally represented as  'h' 'e' 'l' 'l' 'o' '\0'  .It takes 6 chars space i.e 6 byte in memory.

         So sizeof(string) = 6  & strlen(string) = 5 since it doesn't count nul char.  Hence output is  6   5 .

selected by
0 votes
0 votes
first will be 100 , 0 as  character array of 100 will take 100 bytes and length of string is 0 why void foo function is used is not clear to me

Related questions