简体   繁体   English

访问双结构指针,发生分段错误

[英]accessing a double structure pointer, segmentation fault occured

typedef struct
{
        int member;
} mystruct;

void myfunc(mystruct **data)
{
        mystruct *const *p;
        for(p = data; *p !=NULL; p++)
        {
                printf("hello\n");
        }
}

void main(int argc, char *argv[])
{
        myfunc(NULL);
}

tried with the above code am getting segmentation fault, its mainly something wrong in that for loop, how to just remove this segmentation fault in that for loop.... actually am learning this double pointer stuff, so i may be a little stupid in asking few question.... thanks in advance 尝试用上面的代码获取分段错误,它主要是在for循环中出错,如何在该for循环中删除该分段错误....实际上是在学习这种双指针的东西,所以我可能有点愚蠢问几个问题。...在此先感谢

The *p in the for loop dereferences the first pointer. for循环中的*p取消引用第一个指针。 But that pointer is NULL , as you call your function with myfunc(NULL); 但是该指针为NULL ,因为您使用myfunc(NULL);调用了函数myfunc(NULL); .

Whenever you dereference a nullpointer, you invoke undefined behaviour (eg a segmentation fault). 每当取消引用空指针时,就会调用未定义的行为(例如,分段错误)。

typedef struct
{
    int member;
} mystruct;

void myfunc(mystruct **data)
{
    mystruct *const *p;
    // this loop assumes data to be a valid pointer
    // to a NULL-terminated array!
    for(p = data; *p != NULL; p++)
    {
        printf("hello\n");
    }
}

int main()
{
    mystruct s;
    mystruct *arr[2];
    arr[0] = &s; // arr[0] points to s
    arr[1] = NULL; // null-terminator
    s.member = 13;
    myfunc(arr);
    // myfunc(NULL); // undefined behaviour

    return 0;
}

you can fix this by checking data in myfunc: 您可以通过检查myfunc中的data来解决此问题:

void myfunc(mystruct **data)
{
    mystruct *const *p;
    // first check data
    if(data != NULL)
    {
        // loop still assumes data to be a NULL-terminated array!
        for(p = data; *p != NULL; ++p)
        {
            printf("hello\n");
        }
    }
}
...
myfunc(NULL); // well defined as the pointer will be checked

if you just want to iterate over a range, consider the standard approach: 如果只想遍历一个范围,请考虑标准方法:

void myfunc_range(mystruct *begin, mystruct *end)
{
    mystruct const *it;
    for(it = begin; it != end; ++it)
    {
        printf("hello %d\n", it->member);
    }
}

int main()
{
    mystruct s;
    mystruct arr[2];
    s.member = 42;
    myfunc_range(&s, &s + 1); // iterate over a single element
    arr[0].member = 13;
    arr[1].member = 37;
    myfunc_range(arr, arr + sizeof(arr) / sizeof(*arr)); // iterate over the whole array
    myfunc_range(arr + i, arr + i + k); // iterate over elements arr[i..i+k-1]
    myfunc_range(NULL, NULL); // well defined as NULL == NULL (an empty range)
    // myfunc(arr, &s); // undefined behaviour as s is not part of the array arr

    return 0;
}

感谢您的所有答复,恰好现在在for循环的条件部分中访问NULL值时会导致分段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM