I am trying to create an array of fixed-length "strings" in C, but have been having a little trouble. The problem I am having is that I am getting a segmentation fault.
我试图在C中创建一个固定长度的“字符串”数组,但一直有点麻烦。我遇到的问题是我遇到了分段错误。
Here is the objective of my program: I would like to set the array's strings by index using data read from a text file. Here is the gists of my current code (I apologize that I couldn't add my entire code, but it is quite lengthy, and would likely just cause confusion):
这是我的程序的目标:我想使用从文本文件读取的数据按索引设置数组的字符串。这是我当前代码的要点(我道歉,我无法添加我的整个代码,但它很长,可能只会引起混淆):
//"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);
1 个解决方案
#1
4
Note that if your string can be 256 characters long, you need its container to be 257 bytes long, in order to add the final \0
null character.
请注意,如果您的字符串长度为256个字符,则需要其容器长度为257个字节,以便添加最终的\ 0 null字符。
typedef char FixedLengthString[257];
FixedLengthString stringArray[N];
FixedLengthString currentString;
The rest of the code should behave the same, although some casting might be necessary to please functions expecting char*
or const char*
instead of FixedLengthString
(which can be considered a different type depending on compiler flags).
其余的代码应该表现相同,尽管可能需要某些转换来取悦期望char *或const char *而不是FixedLengthString的函数(根据编译器标志可以将其视为不同的类型)。
#1
4
Note that if your string can be 256 characters long, you need its container to be 257 bytes long, in order to add the final \0
null character.
请注意,如果您的字符串长度为256个字符,则需要其容器长度为257个字节,以便添加最终的\ 0 null字符。
typedef char FixedLengthString[257];
FixedLengthString stringArray[N];
FixedLengthString currentString;
The rest of the code should behave the same, although some casting might be necessary to please functions expecting char*
or const char*
instead of FixedLengthString
(which can be considered a different type depending on compiler flags).
其余的代码应该表现相同,尽管可能需要某些转换来取悦期望char *或const char *而不是FixedLengthString的函数(根据编译器标志可以将其视为不同的类型)。