Frage

The code below is related to calculating length of string

#include <stdio.h>

int strl (char *s);
main ()
{
  int len1 = str ("hah");
  printf ("%d", len1);
}


int
str (char *s)
{
  int length = 0;
  while (*s != '\0')
    {
      length++;
      s++;
    }

  return (length);
}

When I call the function str, I am assigning a string literal to pointer and not the address of the string literal to the pointer but it turn out that address is stored. How can pointers store address of "hah" without specifying its address?

War es hilfreich?

Lösung

"hah" is of type char[] so when you pass it to function, it decays to pointer to its first element, as any other array.

Andere Tipps

You don't need to be specifying its address, first of all - you've typed str("hah"); and not strl("hah"); (same when you wrote the function) - the string literal does actaully count as a variable in the function's stack memory and memory is allocated to it. What's more is that when appointing a string literal this way:

char* str = "hah";
char* sstr = "hah";

when printing:

printf("%d %d", str, sstr);

you'd get the same number. Using string literal - the compiler searches for the same string in the memory and if it's not there - it's allocating memory to it. In this case - there WAS a string the same so the addresses the pointers points to would be the same. The correct program would be this way:

#include <stdio.h>
int strl(char *s);
int main()
{ 
    int len1=strl("hah");
    printf("%d",len1);

    return 0;
}
int strl(char *s)
{
    int length=0;
    while (*s!='\0')
    {
        length++;
        s++;
    }

    return (length);
}

just changing str to strl as you mistook str for strl or the opposite :P

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top