【问题标题】:What does the NPTR exactly do and why it's not compiling in c?NPTR 究竟做了什么以及为什么它不在 c 中编译?
【发布时间】:2020-07-29 00:59:18
【问题描述】:

根据我从堆栈溢出中找到的一些代码,我编写了以下代码:

char *split[NPTR] = { NULL }, **p = split;

我不太明白为什么第一个变量应该在一个具有NPTR 并分配了{NULL} 的字符数组中。和char *split[] = NULL 有什么不同吗?

另外,当我运行代码时,代码会吐出以下错误:

error: NPTR' undeclared (first use in this function)
note: each undeclared identifier is reported only once for each function it appears in

【问题讨论】:

  • 看起来应该有一个#define NPTR x,其中x 是要定义的指针数。您可以链接您用作参考的 SO 帖子吗?
  • 感谢您的评论。我发现#define NPTR 32 /* if you need a constant, #define one (or more) */ 包含在其中,所以我假设这个NPTR 会有32 个可能的指针?链接在这里:stackoverflow.com/questions/61148561/…

标签: c pointers null


【解决方案1】:
char *split[] = NULL

初始化无效

char *split[NPTR] = { NULL };

意思是,split 是一个数组,内容为NPTR 指针。每个指针都由NULL初始化。

#define NPTR 32

在您的评论中,这意味着我们将NPTR = 32 定义为一个常量值。

查看以下代码以了解更多信息:

#include <stdio.h>
// define NPTR = 3;
#define NPTR 3

int main()
{
    char * split[NPTR] = {NULL};
    for(int i = 0; i < 3; i++) {
       if(split[i] == NULL)
            printf("ptr[%d] = NULL\n", i);
    }
    split[0] = "abc";
    split[1] = "cdf";
    split[2] = "ijk";

    for(int i = 0; i < 3; i++) {
        printf("%s\n", split[i]);
    }

    return 0;
}

结果:

ptr[0] = NULL                                                                                                           
ptr[1] = NULL                                                                                                           
ptr[2] = NULL                                                                                                           
abc                                                                                                                     
cdf                                                                                                                     
ijk

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 2013-07-28
    • 2016-05-27
    • 1970-01-01
    • 2012-07-23
    • 2016-09-10
    • 2023-03-15
    • 2012-10-17
    • 2021-06-04
    相关资源
    最近更新 更多