字符数组未按预期工作(两个数组的串联)
character array is not working as expected (concatenation of two arrays)
#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的return值不是应该的值,好像没有保存str的值,正确的return应该是"hellolo",但是returns“你好”
函数返回的指针text->str无效,因为它是指向函数内声明的局部数组str的指针,退出函数后不会存活
char str[txt->length];
//...
txt->str=str;
return txt;
还有一个逻辑上的不一致。指针 txt->str 和 txt1->str 指向字符串
txt->str="hello";
txt1->str="lo"
但是指针txt->str并没有指向字符串,因为函数中的数组str没有构建字符串。
您需要动态分配一个数组,而不是本地数组 str,txt->str 将指向该数组。例如
txt->str = malloc( text->length + 1 );
注意这样的typedef声明
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
表示指针类型不清楚
#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的return值不是应该的值,好像没有保存str的值,正确的return应该是"hellolo",但是returns“你好”
函数返回的指针text->str无效,因为它是指向函数内声明的局部数组str的指针,退出函数后不会存活
char str[txt->length];
//...
txt->str=str;
return txt;
还有一个逻辑上的不一致。指针 txt->str 和 txt1->str 指向字符串
txt->str="hello";
txt1->str="lo"
但是指针txt->str并没有指向字符串,因为函数中的数组str没有构建字符串。
您需要动态分配一个数组,而不是本地数组 str,txt->str 将指向该数组。例如
txt->str = malloc( text->length + 1 );
注意这样的typedef声明
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
表示指针类型不清楚