簡體   English   中英

訪問 C (xv6) 中字符數組的單個字符的問題

[英]Problem with Accessing Individual Characters of a Char Array in C (xv6)

我在訪問 C 中的 char 數組中的每個單獨字符時遇到問題。

我這樣聲明 char 數組: char ddd[512]; 作為程序開始時的全局常量。

然后,我使用int n; n = read(fd, ddd, sizeof(ddd));將包含一行隨機字符(如下所示: acdgeud )的文件讀入 char 字符串; int n; n = read(fd, ddd, sizeof(ddd)); . fd代表文件描述符,值為 1。

例如,我想訪問 char 字符串的第二個字符,我嘗試了ddd[1] ,因為這就是我在 C++ 中的做法。 但是,它給了我在第一個字符之后的所有內容: cdgeud

現在,我怎樣才能一次只獲得一個角色? 希望這很清楚,並提前感謝您的幫助!

更新:剛剛添加了部分代碼:

char ddd[512];

void somefunc(int fd) {  

    char *another = malloc(512*sizeof(ddd));   
    int n = 0;

    while ((n = read(fd, ddd, sizeof(ddd))) > 0) {
        if ( n < 0 ) break;
        for (int i = 0; i < n; ++i) {
            /* I'm trying to copy values in ddd to another one by one */
            another[i] = ddd[i];    /* This is not working */
        }
    }
}

(編輯新答案)要逐步完成for您必須在復制值后測試 null 字符。 您也可以在“=”分配之后有一個單獨的休息時間。

for (int i = 0; i < n && (another[i] = ddd[i]); ++i)

為簡單起見,可以使用strncpystrncpy(another, ddd, sizeof another);

確保 \0 終止: while ((n = read(fd, ddd, sizeof(ddd) - 1)) > 0) { ddd[(sizeof ddd)-1) = '\0'; //assure null termination } (original) while ((n = read(fd, ddd, sizeof(ddd) - 1)) > 0) { ddd[(sizeof ddd)-1) = '\0'; //assure null termination } (original)

根據您的評論,我只能猜測而不是正確回答。 這里有一些。

char something[2]; char ddd[512]; int n = read(fd, ddd, sizeof(ddd)); printf("c=%c\n", ddd[1]); // print one character (c) printf("s=%s\n", 1+ddd ); // print cdgeud, and perhaps more // (if memset(ddd,0,sizeof ddd) happened before read things would be better). char another[sizeof(ddd)]; ddd[1] = another[1]; // copy whatever is in another[1] into d[1]. Unpredictable as I coded it as another[] is not initialized printf("s=%s\n", something); // unpredictable... // if something[0] and [1] not '\0' AND ddd follows in memory (not guaranteed at all) // then could print those followed by contentsof ddd.

不保證 ddd 被 \0 終止的事實可能是意外溢出的根源。 這在沒有 memset() 的情況下有效。

n = read( fd, ddd, sizeof ddd ); if ( n <= 0 ) break; // whatever is proper to detect read errors. if ( n < sizeof(ddd) ) ddd[n] = '\0'; printf( "ddd=%.*s\n", n, ddd ); // safe

暫無
暫無

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

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