[英]How to create a dynamic array of strings in C using malloc
How to create an array of strings when there isn't a fixed length of items or characters. 没有固定长度的项目或字符时,如何创建字符串数组。 I'm new to pointers and c in general and I couldn't understand the other solutions posted on here so my solution is posted below.
我是指针和c语言的新手,我听不懂这里发布的其他解决方案,因此我的解决方案发布在下面。 Hopefully it helps someone else out.
希望它可以帮助其他人。
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);}
}
}
// sample program //示例程序
int main(void) {
allocate_2darray(&twod_array, 10, 250); /*allocate 10 arrays of 250 characters each*/
return 0;
}
Simply makes an array from the argv items bar the first item. 只需使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++;
}
Yours is close, but you are allocating the main array too many times. 您的位置接近,但是您分配主数组的次数过多。
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.