top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C: I have one confusion in the following C program related to the string and character array.

+3 votes
595 views
#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 ?

posted Dec 27, 2015 by Harshita

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

2 Answers

0 votes

char ptr[]= {'a','b','c','0','e'};
in above declaration of ptr array.You are not giving '\0' character at last of ptr array so when you will print the length of ptr.You may got length of ptr 5 or other than 5.
But in below of str array declaration
char str[]= "abc0e";
the compiler adjust NULL character at the last of e element.So always you will get length of str array is 5.

answer Dec 27, 2015 by Rajan Paswan
0 votes

Both are giving the length as 5 see the codepad link of your program http://codepad.org/rHdVgNMe

However explanation provided by rajan is correct in one case of str compiler added the '\0' in the end of the string so valid pointer is str[0] - str[5] where as in case of ptr valid ptr is ptr[0] to ptr[4].

answer Dec 28, 2015 by Salil Agrawal
I have checked many compilers e.g. gnu c,turbo c,gnu c++ also.In all cases every compiler giving different different length of ptr array.So check the program on other compilers also.
Yes you are right, codepad may be different. In nutshell there is a difference in both :)
Similar Questions
+5 votes
#include<stdio.h>
#include<string.h>
main()
{
    char p[100];
    int i,len;
    printf("Enter a string\n");
    scanf("%[^\n]",p);
    len=strlen(p);
    for(i=0;i<len-1;i++)
    {
        if(a[i]==a[i+1])
              p[i]=p[i+1];
    }
    printf("String :  %s\n",p);
}
+1 vote

Given an array of integers (possibly some of the elements negative), write a C program to find out the *maximum product* possible by adding 'n' consecutive integers in the array, n <= ARRAY_SIZE.

Also give where in the array this sequence of n integers starts.

...