[英]How to create array of fixed-length “strings” in C?
我正在尝试在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
(取决于编译器标志,可以将其视为不同的类型)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.