double pointer vs pointer to array, incompatible pointer type

后端 未结 3 736
野性不改
野性不改 2021-01-20 16:12

Having this:

#define _DEFAULT_SOURCE 1
#include 
#include 

int main(){
    char *token, org[] = "Cats,Dogs,Mice,,,Dwarves         


        
相关标签:
3条回答
  • 2021-01-20 16:36

    Address of the array references the place where the array starts, it has only the different type - pointer to the array. It is not pointer to pointer.

        char *token, org[] = "Cats,Dogs,Mice,,,Dwarves,Elves:High,Elves:Wood";
        char *pointer = org;
        while((token=strsep(&pointer,",")))
        /* ... */
    

    You cant cast reference to array to double pointer.

    restrict it a quite advanced topic. It promises the compiler that if the object referenced by pointer is modified, the access to this object can be only done by this pointer. It helps the compiler in the code optimisations

    Generally speaking I would not expect you to use this qualifier before you get proficient in the C language.

    0 讨论(0)
  • 2021-01-20 16:39
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        char org[] = "Cats,Dogs,Mice,,,Dwarves,Elves:High,Elves:Wood";
        char *token = strtok(org, ",");
        while (token != NULL) {
            printf("Token: %s\n", token);
            token = strtok(NULL, ",");
        }
    }
    
    

    I think you should take a look at this page : Restrict type qualifier

    0 讨论(0)
  • 2021-01-20 16:42

    The strsep function requires the address of a modifiable pointer as its first argument (or NULL, in which case it does nothing); you are passing it the (fixed) address of an array. You can fix this by declaring a separate char* variable and assigning to that the (address of the) org array:

    int main()
    {
        char* token, org[] = "Cats,Dogs,Mice,,,Dwarves,Elves:High,Elves:Wood";
        char* porg = org; // "porg" is a MODIFIABLE pointer initialized with the start address of the "org" array
        while ((token = strsep(&porg, ",")))
            printf("Token: %s\n", token);
    
        return 0;
    }
    

    From the Linux manual page (bolding mine):

    If *stringp is NULL, the strsep() function returns NULL and does nothing else. Otherwise, this function finds the first token in the string *stringp, that is delimited by one of the bytes in the string delim. This token is terminated by overwriting the delimiter with a null byte ('\0'), and *stringp is updated to point past the token. In case no delimiter was found, the token is taken to be the entire string *stringp, and *stringp is made NULL.

    On the meaning and use of the restrict keyword, maybe this will help: Realistic usage of the C99 'restrict' keyword?.

    0 讨论(0)
提交回复
热议问题