C style strings, Pointers, arrays

前端 未结 3 709
自闭症患者
自闭症患者 2021-02-01 09:46

I\'m having trouble understanding what a C-style string is. Happy early New Year

What I know: A pointer holds a memory address. Dereferencing the pointer will give you

3条回答
  •  轮回少年
    2021-02-01 10:00

    You are asking two questions here, one of which is more general and which I will answer first.

    A pointer is a 'handle' (called an address) to a location in memory. The contents of that location is a value. How that value is interpreted is dependent on the 'type' of the pointer. Think of it this way: an address is the location of a house, for example, 10 Main Street. The contents of 10 Main Street are the contents of the house at that address. In C (and C++) terms:

    int *p;
    

    Is a variable that can hold the address of an integer.

    int x;
    

    Is a variable that IS an integer.

    p = &x;
    

    Has p 'point to' x by storing in p the ADDRESS of x.

    x = 10;
    

    Stores in x the value 10.

    *p == x
    

    Because *p says to 'use the contents of p' as a value and then compare it to x.

    p == &x
    

    Because &x says to 'use the address of x' as a value and then compare it to p, which is a variable of type pointer.

    A string, which is a sequence of zero or more characters is represented in C (and C++) by the characters " and ". In memory, these values are stored consecutively and are automatically terminated by a trailing null byte, which is a byte with the value 0. The string "Hello, world!" is stored in memory, assuming you are using an 8 bit ASCII character encoding, as:

    65 101 108 108 111 44 32 87 111 114 108 33 0

    You can see this for yourself using the following code snippet:

    char *p = "Hello, World!";
    int len = strlen(p);
    int i;
    
    for (i = 0; i <= len;  ++i)
    {
        std::cout << std::dec << (int) p[i] << ' ';
    }
    std::cout << std::endl;
    

    Since the null (zero byte) is automatically added to a constant string by the compiler, the following two arrays are the same size:

    char a1[7] = { 'H', 'i', ' ', 'y', 'o', 'u', '\0' };
    char a2[] = "Hi you";
    
    std::cout << strcmp(a1, a2) << std::endl
    

    Simply put, a 'C style string' is simply an array of characters terminated by a null, which answers your first question.

提交回复
热议问题