【发布时间】:2015-02-23 02:52:47
【问题描述】:
所以我有这段代码,它构建了一个字符串数组(23 个不同大小的字符串)。 为此,我分别定义了每个字符串,如下所示:
char text1[] = "The content of string 1\n";
char text2[] = "The content of string 2 which is longer\n";
剩下的 21 个字符串也是如此。然后我为每个字符串定义了 23 个指向 char 的指针,如下所示:
char *ptext1 = text1;
char *ptext2 = text2;
剩下的 21 个字符串也是如此。然后我定义了一个指向 char 的指针数组,并用我刚刚创建的 23 个指针对其进行了初始化:
char *parray[23];
parray[0] = ptext1;
parray[1] = ptext2; // ...etc.
现在,为了按索引访问字符串,我使用 for 循环遍历元素:
for (i = 0; i < 23; i++)
{
printf("%s", parray[i]);
}
这段代码在 main 函数中就像一个魅力,然而,当我将所有的字符串、指针和数组定义移动到一个头文件时(因为我认为将定义排除在外是一个好习惯,对吧?)并将其包含在 main.c 文件中,在那里我只有 for 循环,但它不起作用。编译器会显示各种警告和错误,例如:
warning: Data definition has to type or storage class (Then it shows this line:) parray[0] = text1;
error: Conflicting types for 'parray'
note: Previous declaration of 'parray' was here: char *parray[23];
error: Invalid Initialized parray[0] = text1;
它继续显示所有 23 个元素的类似警告和错误。
那么为什么这段代码在主函数中像我想要的那样工作,但在我包含它时却没有?
注意:
我正在为 windows 使用 mingw gcc 编译器,当我编译时,我使用这个命令:gcc main.c
而且头文件当然在同一个目录下。
这是一个副本/过去或错误输出:
In file included from x.c:2:0:
x.h:15:2: warning: data definition has no type or storage class [enabled by default]
parray[0] = ptext11;
^
x.h:15:2: error: conflicting types for 'parray'
x.h:13:8: note: previous declaration of 'parray' was here
char *parray[2];
^
x.h:15:2: error: invalid initializer
parray[0] = ptext11;
^
x.h:16:2: warning: data definition has no type or storage class [enabled by default]
parray[1] = ptext12;
^
x.h:16:2: error: conflicting types for 'parray'
x.h:13:8: note: previous declaration of 'parray' was here
char *parray[2];
^
x.h:16:2: error: invalid initializer
parray[1] = ptext12;
^
这是 main.c 文件:
#include <stdio.h>
#include "main.h"
void main(void)
{
int i;
for (i = 0; i < 2; i++)
{
printf("%s", parray[i]);
}
}
还有main.h文件:
char text11[] = "Content of string 1";
char text12[] = "Content of string 2, which is longer";
char *ptext11 = text11, *ptext12 = text12;
char *parray[2];
parray[0] = ptext11;
parray[1] = ptext12;
【问题讨论】:
-
请创建一个MCVE 来说明您的问题。
-
您的错误消息中有印刷错误,您可以剪切并粘贴它,而不是尝试手动转录。
-
text1和text2是chars,只能容纳一个字符。 -
@CoolGuy,不,text1 和 text2 是字符串,我测试了这段代码,工作如我所愿
-
查看您发布的内容。
char text1="..."和char text2=".."。这些不是字符数组。