如何解决C: 重新分配无效指针?
这是我在学校的任务: 编写一个函数 insertString ,将字符串 s2 插入到索引 n 处的 s1 中。s1 已使用 malloc 分配并应调整大小(该函数再次无效)。
程序在 PC 上给了我一个 NULL,当我切换到手机时,编译器说我的 realloc 有一个无效的指针。但我真的不知道我做错了什么。
代码如下:
void insertString(char *str1,char *str2,int n){
int lengStr2=strlen(str2);
printf("%d %d ",lengStr2,n);
printf("\nstr1= %s,str2: %s,n: %d ",str1,str2,n);
str1=(char*)realloc(str1,lengStr2+n+1);
if (str1==NULL){
printf("Error\n");
free(str1);
return -1;
}
printf("\nstr1= %s,n);
memcpy(str1+n,lengStr2+1);
printf("\nstr1= %s,n);
}
void testInsertString( char *str2,int n,char *expect){
char*str1=(char*)malloc(3*sizeof(char));
str1="hoi";
printf("\nstr1= %s,n);
insertString(str1,n);
printf("--> result:%s --> ",str1);
(strcmp(str1,expect)==0)?printf("Success"): printf("Failure");
free(str1);
printf("\nIs Free\n");
}
这里的输出:
str1= hoi,str2: Hallo,n: 1 5 1
str1= hoi,n: 1 Error
--> result:hoi --> Failure
Is Free
Process returned 0 (0x0)
如果你知道我做错了什么,你能告诉我正确的版本吗?即便如此,我也有一个问题,我不能仅仅通过阅读文本来正确地纠正程序,我需要看看它应该如何编写。所以我需要看到正确的结果才能从错误中吸取教训 ^^”(这就是为什么学校里的一些东西对我来说真的很难)。提前致谢 ^^
解决方法
char *str1 = malloc(3*sizeof(char)); /* Allocate memory */
str1="hoi"; /* Discard the only reference to the allocated memory */
以上两行在精神上类似于:
int x = 5; x = 7;
需要将字符串“hoi”复制到新分配的内存中,并且需要至少分配4个字节来保存字符串“hoi”。例如:
char *hoi = "hoi";
char *str1 = malloc(strlen(hoi) + 1);
if( str1 == NULL ){
perror("malloc");
exit(EXIT_FAILURE);
}
sprintf(str1,"%s",hoi);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。