Passing a string literal as a function parameter defined as a pointer

前端 未结 6 946
南旧
南旧 2021-02-05 20:19

I am reading the chapter on arrays and pointers in Kernighan and Richie\'s The C Programming Language.

They give the example:

/* strlen:  return         


        
6条回答
  •  既然无缘
    2021-02-05 20:38

    To understand how a string like "Hello World" is converted to a pointer, it is important to understand that, the string is actually hexadecimal data starting at an address and moving along till it finds a NULL

    So that means, every string constant such as "Hello World" is stored in the memory somewhere

    Possibility would be:

    0x10203040 : 0x48 [H]
    0x10203041 : 0x65 [e]
    0x10203042 : 0x6C [l]
    0x10203043 : 0x6C [l]
    0x10203044 : 0x6F [o]
    0x10203045 : 0x20 [' ']
    0x10203046 : 0x57 [W]
    0x10203047 : 0x6F [o]
    0x10203048 : 0x72 [r]
    0x10203049 : 0x6C [l]
    0x1020304A : 0x64 [d]
    0x1020304B : 0x00 [\0]
    

    So, when this function is called with the above values in the memory, [left side is address followed by ':' and the right side is ascii value of the character]

    int strlen(const char *s)
    {
        int n;
    
        for (n = 0; *s != ′\0′; s++)
            n++;
        return n;
    }
    
    strlen("Hello World");
    

    at that time, what gets passed to strlen is the value 0x10203040 which is the address of the first element of the character array.

    Notice, the address is passed by value.. hence, strlen has its own copy of the address of "Hello World". starting from n = 0, following uptil I find \0 in the memory, I increment n and also the address in s(which then gets incremented to 0x10203041) and so on, until it finds \0 at the address 0x1020304B and returns the string length.

提交回复
热议问题