簡體   English   中英

將元素附加到 C 中的字符串數組中

[英]Appending element into an array of strings in C

我有一個給定大小的字符串數組,不使用任何內存分配,我如何在其中添加一些內容?

假設我運行代碼,它在等待你想要輸入的東西,你輸入"bond" ,我如何將它附加到一個數組中? [10] ?

如果數組聲明為

char A[10];

然后您可以通過以下方式為其分配字符串“bond”

#include <string.h>

//...

strcpy( A, "bond" );

如果你想用其他字符串追加數組,那么你可以寫

#include <string.h>

//...

strcpy( A, "bond" );
strcat( A, " john" );

您不能附加到數組。 當您定義數組變量時,C 會詢問是否有足夠的連續內存。 這就是你得到的所有記憶。 您可以修改數組的元素 (A[10]=5) 但不能修改大小。

但是,您可以創建允許附加的數據結構。 最常見的兩種是鏈表和動態數組。 請注意,這些不是內置於語言中的。 您必須自己實現它們或使用庫。 Python、Ruby 和 JavaScript 的列表和數組是作為動態數組實現的。

LearnCThHardWay 有一個關於鏈表的非常好的教程,盡管關於動態數組的教程有點粗糙。

你好,

這真的取決於你所說的附加是什么意思。

...
int tab[5]; // Your tab, with given size
// Fill the tab, however suits you.
// You then realize at some point you needed more room in the array
tab[6] = 5; // You CAN'T do that, obviously. Memory is not allocated.

這里的問題可能是兩件事:

  • 您是否誤判了您需要的尺寸? 在這種情況下,只需確保您提到的這個給定尺寸是正確“給定”的,但可能是這樣。
  • 或者你一開始不知道你想要多少空間? 在這種情況下,您必須自己分配內存! 如果我可以說,沒有其他方法可以即時調整內存塊的大小。


    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define STR_MAX_SIZE 255                                // Maximum size for a string. Completely arbitray.
char *new_string(char *str) { char *ret; // The future new string;
ret = (char *) malloc(sizeof(char) * 255); // Allocate the string strcpy(ret, str); // Function from the C string.h standard library return (ret); }
int main() { char *strings[STR_MAX_SIZE]; // Your array char in[255]; // The current buffer int i = 0, j = 0; // iterators
while (in[0] != 'q') { printf("Hi ! Enter smth :\n"); scanf("%s", in); strings[i] = new_string(in); // Creation of the new string, with call to malloc i++; } for ( ; j < i ; j++) { printf("Tab[ %d ] :\t%s\n", j, strings[j]); // Display free(strings[j]); // Memory released. Important, your program // should free every bit it malloc's before exiting }
return (0); }


這是我能想到的最簡單的解決方案。 這可能不是最好的,但我只是想向您展示整個過程。 我可以使用 C 標准庫strdup(char *str)函數來創建一個新字符串,並且可以實現我自己的快速列表或數組。

數組變量的大小不能改變。 追加到數組的唯一方法是使用內存分配。 您正在尋找realloc()函數。

如果你想向它附加一個字符或字符串;

strcpy(a, "james")
strcpy(a, "bond")

暫無
暫無

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

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