簡體   English   中英

字符串與2d數組C比較

[英]String Compare with 2d array C

我正在考慮將字符串復制到2d數組。 我有一個2d char數組,初始化為char labels[100][2]所以它是100 * 2數組。 我希望每一行的第一列都包含一個字符串,並且我知道您不能簡單地分配一個字符串,您必須進行字符串復制。 我的想法是我可以做到:

strcpy(labels[1][0],"hi");//The compiler doesn't like this

經過研究,我發現您可以執行以下操作:

strcopy(labels[1],"hi")

我對此很好奇,因為此strcpy處於for循環中,所以我最多可能有十個副本,而且我不知道這是否每次都只能正確復制到第一列。

要處理2D數組的列,您可以按以下方式進行:

char labels[100][2], (*p)[2], i;
....

for (p = &labels[i]; p < &labels[100]; P++)
    (*P)[i] = //assign a char

我對您的陳述“您不能簡單地分配一個字符串”感到好奇。 的確如此,但是您可以將指針分配給字符串文字。 為什么不將其簡化如下:

char *labels[100];

labels[0] = "hi";
labels[1] = "bye";
labels[2] = "arbitrary-length string literal";
....

這比處理2d數組,strcpy()等要簡單得多。

同樣,strcpy()通常被認為是不安全的

如果您需要將label + address保留在單個7個字符的字符串中,那么最簡單的方法是:

#define MAX_LABELS 100
char labels[MAX_LABELS][7];

// do something with the array
for (int i=0; i<MAX_LABELS; i++) {
   strcpy(labels[i], "label");  // watch for buffer overflow here
   labels[i][6] = (char)i;
}

或者,如果標簽和地址是否在同一字符串中也沒關系,請使用結構數組使代碼更具可讀性:

struct LabelStruct {
    char label[6];
    char address[1];
} labels[MAX_LABELS];

// do something with the array
for (int i=0; i<MAX_LABELS; i++) {
    strcpy(labels[i].label, "label");  // watch for buffer overflow here
    labels[i].address = (char)i;
}

您沒有說是否需要以null終止的標簽,但是,如果需要,可以在標簽數組中再添加一個char。 同樣,在將數據分配給標簽時,請檢查是否溢出(使用strncpy或類似方法)。

暫無
暫無

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

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