[英]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.