我正在尝试构build一个dynamic增长的string数组。 在编译时,string的数量和每个string的长度都是已知的。 这里是我到目前为止的代码(这只是我玩的语法):
char **result = NULL; char *temp = NULL; result = (char **)realloc (result,sizeof(char *) * 1); temp= (char *)realloc(temp,5 * sizeof(char)); strcat(temp,"hello"); temp= (char *)realloc(temp,10 * sizeof(char)); strcat(temp," world"); printf ("%s n",temp); result[0]=temp; free(temp); printf ("%s n",result[0]); result = (char **)realloc (result,sizeof(char *) * 2); temp= (char *)realloc(temp,"0123456789"); temp= (char *)realloc(temp,15 * sizeof(char)); strcat(temp,"asdfg"); printf ("%s n",temp); result[1]=temp; free(temp); printf ("%s n",result[0]); printf ("%s n",result[1]);)
现在,当我打印结果[0]或结果[1]时,它只是一个空string,为什么不会导致[1] = temp; 工作?
这是我以前的尝试,但它不起作用,我在最后一行使用realloc()时一直得到“无效大小”错误:
char **result = NULL; result = (char **)realloc (result,sizeof(char *) * 1); result[0]= (char *)realloc(result[0],5 * sizeof(char)); strcat(result[0],"hello"); printf ("%s n",result[0]); result[0]= (char *)realloc(result[0],10 * sizeof(char)); strcat(result[0],sizeof(char *) * 2); result[1]= (char *)realloc(result[1],"0123456789"); result[0]= (char *)realloc(result[1],15 * sizeof(char)); strcat(result[0],"asdfg");
如果有人能帮助我得到任何版本的工作,我将非常感激。
没有SDL的stdout.txt
如何导入公共.pem dsa密钥到C#代码?
分析崩溃
为C / C ++标准libs,boost和第三方库设置单独的ctags db
更新:好吧,我有两个版本的代码工作。 现在,当我尝试在我的实际程序中使用相同的格式时,出现如下错误
*** glibc detected *** ./uvicfmt3: realloc(): invalid next size: 0x08ed3170 ***
现在在我的程序中,“结果”被声明为一个全局variables(使用我的代码的第二个版本),并且realloc函数在不同的子程序中被调用。 这是什么原因造成的问题? 我怎么能解决这个问题?
可从Java访问的Linux中的registry级别计数器
调用IWebbrowser2-> get_Document时错误800706B5
是否可以使用LD_PRELOAD覆盖主要方法?
如何在Windows上使用Vim运行“:compiler msvc”和“:comp msbuild”?
以下语句将result[0]和temp点指向相同的内存地址:
result[0]=temp;
完成上述任务之后,您可以free(temp)并尝试访问result[0] :
free(temp); printf ("%s n",result[0]);
这是未定义的行为,因为您正在访问刚被释放的内存。
对于result[1]相同的代码也是如此result[1] 。
在第二个例子中,你正在寻找未分配的内存(加上未受教育的realloc(result[0]没有任何意义)
你可以试试这个:
char **result = NULL; result = realloc(result,sizeof(char *) * 1); result[0] = strdup("hello"); /* ... */ result = realloc(result,sizeof(char *) * 2); result[1] = strdup(" world");
现在strdup不是标准的,但是盗取/伪造并不困难。 这里有一个尝试:
char *strdup2(const char *str) { size_t len; char *rval = NULL; len = strlen(str); /* We should probably check this. */ rval = malloc(len + 1); /* And this. */ memcpy(rval,str,len); rval[len] = 0; return rval; }
编辑
我是(可能是错误的)印象,你想以后修改字符串。 如果情况并非如此,那么简单地存储它们(没有strdup )就足够了:
result[0] = "hello";
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。