C strings confusion

前端 未结 7 2077
深忆病人
深忆病人 2020-11-27 14:30

I\'m learning C right now and got a bit confused with character arrays - strings.

char name[15]=\"Fortran\";

No problem with this - its an

相关标签:
7条回答
  • 2020-11-27 15:08

    One is an actual array object and the other is a reference or pointer to such an array object.

    The thing that can be confusing is that both have the address of the first character in them, but only because one address is the first character and the other address is a word in memory that contains the address of the character.

    The difference can be seen in the value of &name. In the first two cases it is the same value as just name, but in the third case it is a different type called pointer to pointer to char, or **char, and it is the address of the pointer itself. That is, it is a double-indirect pointer.

    #include <stdio.h>
    
    char name1[] = "fortran";
    char *name2 = "fortran";
    
    int main(void) {
        printf("%lx\n%lx %s\n", (long)name1, (long)&name1, name1);
        printf("%lx\n%lx %s\n", (long)name2, (long)&name2, name2);
        return 0;
    }
    Ross-Harveys-MacBook-Pro:so ross$ ./a.out
    100001068
    100001068 fortran
    100000f58
    100001070 fortran
    
    0 讨论(0)
提交回复
热议问题