你需要注意你正在做的事情.您在堆栈中分配了一个char数组,因为它是func
函数的本地数组,并且您将它们分配给作为参数传递的 struct 的一个成员.你有一些 Select 来解决你的问题.一种方法是使用char数组而不是指向char的指针,并完全复制该数组:
#include <stdio.h>
#include <string.h>
#define STRING_SIZE 8
struct TStruct {
char string[STRING_SIZE];
};
void func(struct TStruct *tstruct) {
char chara[STRING_SIZE];
sprintf(chara, "%.*s", 4, "testing");
strncpy( tstruct->string, chara, STRING_SIZE );
}
int main() {
struct TStruct tstruct = {0};
func(&tstruct);
printf("%s", tstruct.string);
return 0;
}
另一种方法是动态分配内存,然后释放内存:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRING_SIZE 8
struct TStruct {
char *string;
};
void func(struct TStruct *tstruct) {
char *chara = (char*) malloc( STRING_SIZE * sizeof(char) );
sprintf(chara, "%.*s", 4, "testing");
tstruct->string = chara;
}
void freeTStruct( struct TStruct *tstruct ) {
free( tstruct->string );
}
int main() {
struct TStruct tstruct = {0};
func(&tstruct);
printf("%s", tstruct.string);
freeTStruct(&tstruct);
return 0;
}
最后,我将实现如下内容:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct MyType {
char *string;
size_t stringLength;
} MyType;
MyType newMyType( const char* string ) {
MyType new = {
.string = NULL,
.stringLength = strlen(string)
};
new.string = (char*) malloc( (new.stringLength+1) * sizeof(char) );
strncpy( new.string, string, new.stringLength+1 );
return new;
}
void freeMyType( MyType *myType ) {
free( myType->string );
}
int main() {
MyType foo = newMyType( "bar" );
printf( "string: \"%s\", length: %d", foo.string, foo.stringLength );
freeMyType( &foo );
return 0;
}