[英]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);
}
strdup(char *str)
函數來創建一個新字符串,並且可以實現我自己的快速列表或數組。
數組變量的大小不能改變。 追加到數組的唯一方法是使用內存分配。 您正在尋找realloc()
函數。
如果你想向它附加一個字符或字符串;
strcpy(a, "james")
strcpy(a, "bond")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.