【发布时间】:2021-12-12 23:35:27
【问题描述】:
#include <stdio.h>
typedef struct _Text {
char *str; //pointer to string
int length; //length of the text
int counter; //counter of text pointing this struct
} *Text;
Text concat(Text txt1, Text txt2){
Text txt= malloc(sizeof(*txt));
txt->length=txt1->length+txt2->length;
txt->counter=1;
char str[txt->length];
for(int i=0; txt1->length>i;i++){ //first word concat
str[i]=txt1->str[i];
}
for(int i=0; txt2->length>i;i++){ //second word concat
str[i+txt1->length]=txt2->str[i];
}
txt->str=str;
return txt;
}
int main(void) {
Text txt= malloc(sizeof(*txt));
Text txt1= malloc(sizeof(*txt1));
txt->str="hello"; txt->length=5; txt->counter=1;
txt1->str="lo"; txt1->length=2; txt1->counter=1;
concat(txt,txt1);
return 0;
}
concat的返回值不是应该的值,好像没有保存str的值,正确的返回应该是"hellolo",但是返回的是"hello"
【问题讨论】:
-
你需要
mallocstr。否则它只是一个局部变量,一旦函数返回就可能被销毁。 -
不要隐藏带有
typedef的指针。 -
如果我 malloc 的 str 它抛出这个异常:错误:可变大小的对象可能没有被初始化
-
你无法通过暴力破解代码来学习 C。将您的步骤回溯到您学习为字符串分配内存的课程。如果你想动态分配它,它必须是
char *,因为你不能分配给某种char[]。 -
现在解决了,是真的,只需要作为指针就可以了,谢谢哥们
标签: c struct scope concatenation c-strings