嗨,我試圖在 c 中創建一個不確定長度的字串陣列。這是我的代碼:
int main()
{
int lineCount=linesCount();
char text[lineCount][10];
printf("%d",lineCount);
FILE * fpointer = fopen("test.txt","r");
fgets(text,10,fpointer);
fclose(fpointer);
printf("%s",text);
return 0;
}
我想更換 10 英寸
char text[lineCount][10];
我的代碼讀出了一個檔案,我已經將行數設為動態。由于行長是不可預測的,我想用動態的東西替換 10。提前致謝。
uj5u.com熱心網友回復:
為了干凈利落地做到這一點,我們需要一個char *陣列而不是二維char陣列:
char *text[lineCount];
而且,我們需要使用堆中的記憶體來存盤各個行。
另外,不要“硬連線”所謂的“神奇”數字,例如10. 使用enum或#define(例如)#define MAXWID 10。請注意,通過下面的解決方案,我們完全不需要使用幻數。
另外,請注意使用sizeof(buf)下面的而不是幻數。
而且,我們希望在閱讀和列印時使用 [單獨的] 回圈。
無論如何,這是重構后的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
linesCount(void)
{
return 23;
}
int
main(void)
{
int lineCount = linesCount();
char *text[lineCount];
char buf[10000];
printf("%d", lineCount);
// open file and _check_ the return
const char *file = "test.txt";
FILE *fpointer = fopen(file, "r");
if (fpointer == NULL) {
perror(file);
exit(1);
}
int i = 0;
while (fgets(buf, sizeof(buf), fpointer) != NULL) {
// strip newline
buf[strcspn(buf,"\n")] = 0;
// store line -- we must allocate this
text[i ] = strdup(buf);
}
fclose(fpointer);
for (i = 0; i < lineCount; i)
printf("%s\n", text[i]);
return 0;
}
更新:
上面的代碼是從你的原始代碼派生出來的。但是,它假設該linesCount函式可以預測行數。并且,它不會檢查固定長度text陣列的溢位。
這是一個更通用的版本,它將允許任意數量的具有不同行長的行:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(void)
{
int lineCount = 0;
char **text = NULL;
char buf[10000];
// open file and _check_ the return
const char *file = "test.txt";
FILE *fpointer = fopen(file, "r");
if (fpointer == NULL) {
perror(file);
exit(1);
}
int i = 0;
while (fgets(buf, sizeof(buf), fpointer) != NULL) {
// strip newline
buf[strcspn(buf,"\n")] = 0;
lineCount;
// increase number of lines in array
text = realloc(text,sizeof(*text) * lineCount);
if (text == NULL) {
perror("realloc");
exit(1);
}
// store line -- we must allocate this
text[lineCount - 1] = strdup(buf);
}
fclose(fpointer);
// print the lines
for (i = 0; i < lineCount; i)
printf("%s\n", text[i]);
// more processing ...
// free the lines
for (i = 0; i < lineCount; i)
free(text[i]);
// free the list of lines
free(text);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/367097.html
上一篇:有沒有辦法在python中將一個單詞分成3個不同的部分?
下一篇:用變數替換字串
