-1

Suppose the function definition be:

int    strlength    (char    str[])    {
            int    i;
            for(i=1;str[i]!='\0';i++);
            return    i;
        }

It should work only when passing the address of the first block of array i.e. '&str[0]' OR 'str' but it works even on passing a string constant let's say "AnswerPlease". Why?

  • 3
    Why do you thing is should not work " even on passing a string constant"? `strlength()` does not attempt to modify the data pointed to by `str`? – chux - Reinstate Monica Feb 13 '17 at 01:21
  • 1
    String literals are some special stuff different from `char`s and `int`s. Using `"Blahblahblah"` actually stores the string literal somewhere in the memory, Unlike the others, say `'C'` where no memory is allocated for it. As the below answer says, a string literal is a `static const char[]` and you get the address of its first element just as in the case of arrays. – Spikatrix Feb 13 '17 at 02:37

1 Answers1

2

Because the C standard says so. In C the type of a string literal is a char[], only it's static and const.

See What is the type of string literals in C and C++? and Where do I find the current C or C++ standard documents?.

Community
  • 1
  • 1
Neo X
  • 947
  • 7
  • 9