Reading a string with scanf

后端 未结 2 626
逝去的感伤
逝去的感伤 2020-11-22 10:44

I\'m a little bit confused about something. I was under the impression that the correct way of reading a C string with scanf() went along the lines of

(

2条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 11:01

    I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.

    char str[]  
    
    1. array of values of type char, with its own address in memory
    2. array of values of type char, with its own address in memory as many consecutive addresses as elements in the array
    3. including termination null character '\0' &str, &str[0] and str, all three represent the same location in memory which is address of the first element of the array str

      char *strPtr = &str[0]; //declaration and initialization

    alternatively, you can split this in two:

    char *strPtr; strPtr = &str[0];
    
    1. strPtr is a pointer to a char
    2. strPtr points at array str
    3. strPtr is a variable with its own address in memory
    4. strPtr is a variable that stores value of address &str[0]
    5. strPtr own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])
    6. &strPtr represents the address of strPtr itself

    I think that you could declare a pointer to a pointer as:

    char **vPtr = &strPtr;  
    

    declares and initializes with address of strPtr pointer

    Alternatively you could split in two:

    char **vPtr;
    *vPtr = &strPtr
    
    1. *vPtr points at strPtr pointer
    2. *vPtr is a variable with its own address in memory
    3. *vPtr is a variable that stores value of address &strPtr
    4. final comment: you can not do str++, str address is a const, but you can do strPtr++

提交回复
热议问题