簡體   English   中英

c 中的動態數組字符串

[英]Dynamic array strings in c

我有一個任務,我應該逐行讀取一個文本文件,然后我應該反轉行(該行包含一個字符串),同時我必須反轉行的順序,所以最后一個應該是第一個應該是第二個,依此類推,我必須將所有這些都寫在標准 output 上。

首先,我應該從 argv[] f 中讀取一個枚舉,它可以是“linenums”或“nolinenums”,如果它是“nolinenums”我無事可做,但對於“linenums”我必須向后編號。 然后一個 int 和另一個 arguments 應該是文件的名稱。

一個例子:./main linenums 5 example.txt
輸入:

  • 蘋果

output:

  • 3 轉載
  • 2 賽跑
  • 1 埃爾帕

該任務說我必須使用動態數組來存儲行,我無法在讀取行之前計算文件的行數,如果行數大於動態數組的大小,我應該將其大小加倍。

好吧,我做了一些事情,但有點亂,我知道這個網站不是為了完全完成我的任務,但我會非常感激,但任何幫助都會很好。 (我的時間也很有限)

這是我到目前為止所做的:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef enum Type{
linenums,
nolinenums
}Type;

struct str{
Type type;
int length;
};

#define BUFFERSIZE 50

int main(int argc, char *argv[])
{
struct str Data;

if(argc < 3)
{
    printf("\trev [SHOW LINE NUMBERS] [MAX LINE LENGTH] files...\n");
    exit(1);
}

if(strcmp(argv[1], "linenums") == 0)
{
    Data.type = linenums;
}
else if(strcmp(argv[1], "nolinenums") == 0)
{
    Data.type = nolinenums;
}
else
{
    printf("Wrong format!");
    exit(1);
}

Data.length = atoi(argv[2]);

for(int i=3; i<argc; i++)
{
    FILE *fpin = fopen(argv[i], "r");
    char buffer[BUFFERSIZE];
    
    int lines = 0;

    if(fpin == NULL)
    {
        fprintf(stderr, "File opening unsuccessful: %s", argv[i]);
        exit(1);
    }
    else
    {   
        char **words = malloc(sizeof(char) * 8);
        for(int i = 0; i < 8; i++)
        {
            words[i] = malloc(sizeof(char*) * 1025);
            if(words[i] == NULL)
            {
                printf("Memory allocation unsuccesful");
                exit(1);
            }
        }

        while(fgets(buffer, BUFFERSIZE, fpin) != NULL)
        {
            buffer[strcspn(buffer, "\n")] = '\0';
            strrev(buffer);
            strcpy(words[lines], buffer);
            lines += 1;
        }
        if(Data.type == 0)
        {
            while(lines>0)
            {
                printf("%d %s\n", lines, words[lines-1]);
                lines -= 1;
            }
        }
        else
        {
            while(lines>0)
            {
                printf("%s\n", words[lines-1]);
                lines -= 1;
            }
        }
        
        printf("\n");
    }
    fclose(fpin);
}

return 0;
}

我的主要問題是動態數組和遍歷 argv[] 數組

多虧了 pm100,我的 output 與示例是正確的,但是當我必須處理多個文件時我仍然遇到問題,並且當行數多於已分配的行數時我仍然必須執行重新分配(我應該加倍)。

根本問題在這里

 words[lines] = buffer;

這不會復制字符串,而是替換單詞數組中的指針(指向您剛剛在上面分配的 memory)

你需要

  strcpy(words[lines], buffer);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM