【问题标题】:Pointer-to-pointer arithmetic not behaving as expected [duplicate]指针对指针算法的行为不符合预期[重复]
【发布时间】:2017-10-08 01:08:02
【问题描述】:

我有下面的代码,但不明白为什么会出现段错误。我在哪里搞砸了。我正在尝试学习如何访问/修改 char **。谢谢!

#include <stdio.h>
#include <stdlib.h>

int main() {
    char * wordPtr;
    char **wordPtrPtr = &wordPtr;
    *wordPtrPtr = (char *) malloc(3 * sizeof(char));

    *wordPtrPtr[0] = 'A';
    *wordPtrPtr[1] = 'B';
    *wordPtrPtr[2] = '\0';

    printf("%s\n", *wordPtrPtr);

    return 0;
}

【问题讨论】:

  • *wordPtrPtr[index] --> (*wordPtrPtr)[index]

标签: c arrays pointers segmentation-fault pointer-to-pointer


【解决方案1】:

注意operator precedence。在访问数组元素之前,您需要先取消引用wordPtrPtr

(*wordPtrPtr)[0] = 'A';
(*wordPtrPtr)[1] = 'B';
(*wordPtrPtr)[2] = '\0';

【讨论】:

  • wordPtrPtr[0][0] = …
【解决方案2】:

你也可以试试这样的

 wordPtr[0] = 'A';
 wordPtr[1] = 'B';
 wordPtr[2] = '\0';

或者

*(*wordPtrPtr +0) = 'A';
*(*wordPtrPtr +1) = 'B';
*(*wordPtrPtr +2) = '\0';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-27
    • 2015-05-15
    • 2021-12-07
    • 2012-01-13
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    相关资源
    最近更新 更多