我必须存储一些在c代码的args中给出的字符串。我遍历了它们,但是我不能正确地存储它们,因为我不知道它们的长度,也不知道它们的数量。更好的方法应该是2d指针数组,这样我就可以为每个新字符串动态分配内存。问题是我是c语言的新手,对此技术我感到很困惑。我试图初始化一个双指针并使用函数插入元素,它为另一列(新字符串)分配空间并设置长度(字符串大小)。
char** files;
int files_i=0;
void insert(char** root,char[] str)
{
root=(char **)malloc(sizeof(char *));
root[files_i]=(char *)malloc(sizeof(char)*sizeof(str));
root[files_i*sizeof(str)]=str;
i++;
}
我将双指针和需要“附加”的字符串传递给该函数。它不起作用,我也非常怀疑如何进行迭代...
strlen(str)
代替sizeof(str)
来计算字符串长度。root[files_i]= malloc(strlen(str) + 1); // +1 for null character at the end of the string
if(!root[file_i]) {return;}
strcpy
而不是=
运算符。或使用strdup
(如果使用strdup
,则不需要为字符指针分配内存)。strcpy(root[files_i],str); // copy string str to "file_i" position of array root
file_i
,则应将realloc
用作根,因为root
的大小必须有所不同(我认为是错字,i++
应该更改为file_i++
吗?) 。 root= realloc(root, sizeof(char *) * (file_i + 1));
// do not forget to check the return value of malloc or realloc function.
if(!root) {return;}
malloc
或realloc
功能。参见Do I cast the result of malloc?您需要的是以下
char** files = NULL;
size_t files_i = 0;
//...
int insert( char ***root, const char str[], size_t i )
{
char *p = malloc( strlen( str ) + 1 );
int success = p != NULL;
if ( success )
{
char **tmp = realloc( *root, ( i + 1 ) * sizeof( char * ) );
if ( success )
{
strcpy( p, str );
tmp[i] = p;
*root = tm;l
}
else
{
free( p );
}
}
return success;
}
然后在呼叫者中您可以编写例如
if ( insert( &root, some_string, i ) ) ++i;