我正在尝试用 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(¤tString, 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], ¤tString);
请注意,如果您的字符串长度可以为 256 个字符,则其容器的长度需要为 257 个字节,以便添加最后的
\0
空字符。
typedef char FixedLengthString[257];
FixedLengthString stringArray[N];
FixedLengthString currentString;
代码的其余部分应该表现相同,尽管可能需要进行一些转换才能满足期望
char*
或 const char*
而不是 FixedLengthString
的函数(根据编译器标志,可以将其视为不同的类型)。