[英]How to create a dynamic array of strings in C using malloc
沒有固定長度的項目或字符時,如何創建字符串數組。 我是指針和c語言的新手,我聽不懂這里發布的其他解決方案,因此我的解決方案發布在下面。 希望它可以幫助其他人。
char **twod_array = NULL;
void allocate_2darray(char ***source, int number_of_slots, int length_of_each_slot)
{
int i = 0;
source = malloc(sizeof(char *) * number_of_slots);
if(source == NULL) { perror("Memory full!"); exit(EXIT_FAILURE);}
for(i = 0; i < no_of_slots; i++){
source[i] = malloc(sizeof(char) * length_of_each_slot);
if(source[i] == NULL) { perror("Memory full!"); exit(EXIT_FAILURE);}
}
}
//示例程序
int main(void) {
allocate_2darray(&twod_array, 10, 250); /*allocate 10 arrays of 250 characters each*/
return 0;
}
只需使argv項目欄中的數組成為第一個項目即可。
char **dirs = NULL;
int count = 0;
for(int i=1; i<argc; i++)
{
int arraySize = (count+1)*sizeof(char*);
dirs = realloc(dirs,arraySize);
if(dirs==NULL){
fprintf(stderr,"Realloc unsuccessful");
exit(EXIT_FAILURE);
}
int stringSize = strlen(argv[i])+1;
dirs[count] = malloc(stringSize);
if(dirs[count]==NULL){
fprintf(stderr,"Malloc unsuccessful");
exit(EXIT_FAILURE);
}
strcpy(dirs[count], argv[i]);
count++;
}
您的位置接近,但是您分配主數組的次數過多。
char **dirs = NULL;
int count = 0;
dirs = malloc(sizeof(char*) * (argc - 1));
if(dirs==NULL){
fprintf(stderr,"Char* malloc unsuccessful");
exit(EXIT_FAILURE);
}
for(int i=1; i<argc; i++)
{
int stringSize = strlen(argv[i])+1;
dirs[count] = malloc(stringSize);
if(dirs[count]==NULL){
fprintf(stderr,"Char malloc unsuccessful");
exit(EXIT_FAILURE);
}
strcpy(dirs[count], argv[i]);
count++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.