如何在 C 中创建固定长度 "strings" 的数组?
How to create array of fixed-length "strings" in C?
我试图在 C 中创建一个固定长度的数组 "strings",但遇到了一些麻烦。我遇到的问题是我遇到了 分段错误 。
这是我的程序的 objective:我想使用从文本文件读取的数据按索引设置数组的字符串。这是我当前代码的要点(很抱歉我无法添加我的整个代码,但它很长,并且可能只会引起混淆):
//"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 个字节,以便添加最后的 [=11=]
空字符。
typedef char FixedLengthString[257];
FixedLengthString stringArray[N];
FixedLengthString currentString;
其余代码的行为应该相同,尽管可能需要一些转换来取悦期望 char*
或 const char*
而不是 FixedLengthString
的函数(这可以被认为是不同的类型取决于编译器标志)。
我试图在 C 中创建一个固定长度的数组 "strings",但遇到了一些麻烦。我遇到的问题是我遇到了 分段错误 。
这是我的程序的 objective:我想使用从文本文件读取的数据按索引设置数组的字符串。这是我当前代码的要点(很抱歉我无法添加我的整个代码,但它很长,并且可能只会引起混淆):
//"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 个字节,以便添加最后的 [=11=]
空字符。
typedef char FixedLengthString[257];
FixedLengthString stringArray[N];
FixedLengthString currentString;
其余代码的行为应该相同,尽管可能需要一些转换来取悦期望 char*
或 const char*
而不是 FixedLengthString
的函数(这可以被认为是不同的类型取决于编译器标志)。