簡體   English   中英

以相反的順序打印字符串數組中的字符串

[英]printing strings in array of strings in reverse order

所以我做了這個程序,目的是從標准輸入存儲一個字符串並存儲在一個字符串數組中。 之后,我想打印存儲在數組中的所有字符串,但順序相反。

例子:

輸入:

abc def hij klm nop

Output:

nop
klm
hij
def
abc

程序:

#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
#define MAXLEN 1001

int main(){
    char buffer[MAXLEN];
    char** strings;
    int i = 0;
    int j = MAXLEN;
    strings = (char**)malloc(sizeof(char*)*MAXLEN);
    while(scanf("%s",buffer) == 3)
    {
        strings[i]=(char*)malloc(sizeof(char)*(strlen(buffer)+1));
        strcpy(strings[i],buffer);
        i++;
    }
    printf("%s",strings[0]);
}

好吧,我只是把第一個字符串只是為了檢查它是否正在打印任何字符串問題是如果在示例中鍵入它會打印(null)而不是單詞,我想知道為什么它指向 NULL 而不是指向到我給的字符串。

真的任何幫助將不勝感激。

stdin成功轉換的測試不正確: scanf()返回轉換次數,而不是字符數。 您應該將返回值與1進行比較。 按照編碼,循環測試立即失敗,因此不會修改strings[0] ,代碼具有未定義的行為,因為malloc分配的數組未初始化。 This array happens to contain a null pointer at the beginning (because its first bytes are zero by coincidence), and printf prints (null) for null pointers, which is not guaranteed by the C Standard, but a useful indication sometimes.

此外,您應該告訴scanf()要存儲到目標數組中的單詞的最大長度: scanf("%1000s", buf)

您還應該限制撕入指針數組的字數並測試 memory 分配錯誤。

最后,您需要以與輸入相反的順序循環到 output 字符串。

這是修改后的版本:

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

#define MAXLEN 1001

int main() {
    char buffer[MAXLEN];
    int i, j;
    char **strings = malloc(sizeof(char *) * MAXLEN);
    if (strings == NULL)
        return 1;
    for (i = 0; i < MAXLEN && scanf("%1000s", buffer) == 1; i++) {
        strings[i] = strdup(buffer);
        if (strings[i] == NULL)
            return 1;
    }
    for (j = i; j-- > 0;) {
        printf("%s\n", strings[j]);
        free(strings[j]);
    }
    free(strings);
    return 0;
}

暫無
暫無

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

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