如何在C中创建固定长度的"字符串"数组?

use*_*690 6 c arrays string char low-level

我试图在C中创建一个固定长度的"字符串"数组,但一直有点麻烦.我遇到的问题是我遇到了分段错误.

这是我的程序的目标:我想使用从文本文件读取的数据按索引设置数组的字符串.这是我当前代码的要点(我道歉,我无法添加我的整个代码,但它非常冗长,可能只会引起混淆):

//"n" is set at run time, and 256 is the length I would like the individual strings to be
char (*stringArray[n])[256];
char currentString[256];

//"inputFile" is a pointer to a FILE object (a .txt file)
fread(&currentString, 256, 1, inputFile);
//I would like to set the string at index 0 to the data that was just read in from the inputFile
strcpy(stringArray[i], &currentString);
Run Code Online (Sandbox Code Playgroud)

Cya*_*yan 5

请注意,如果您的字符串长度可以为 256 个字符,则您需要其容器长度为 257 个字节,以便添加最后的\0空字符。

typedef char FixedLengthString[257];
FixedLengthString stringArray[N];
FixedLengthString currentString;
Run Code Online (Sandbox Code Playgroud)

代码的其余部分应该表现相同,尽管可能需要进行一些转换来满足期望char*或const char*替代的函数FixedLengthString(根据编译器标志,可以将其视为不同的类型)。

  • `char stringArray[n][256];` 也可以工作,无需引入数组 typedef (这会混淆代码,恕我直言)。 (2认同)