我没有从以下获得字符串输出:
结构字符串项 {
国际化;
字符 str[1];
}
void allocationStringBuffer (char* stringContent, struct stringItem *string) {
// dynamically sized object
int n;
n = strlen(stringContent);
//struct stringItem *string = malloc(sizeof(struct stringItem) + n);
string = malloc(sizeof(struct stringItem) + n);
if (string == NULL) { // check if malloc is successful
printf("Memory allocation for string fails.\n");
// exit(-1);
}
strcpy(string->str, stringContent);
printf("Struct string: %s\n", string->str);
string->len = n;
}
主要:
struct stringItem *string2;
allocationStringBuffer ("helloWorld", string2);
printf("Struct string: %s\n", (*string2).str);
free(string2);
allocationStringBuffer ("another Statement...", string2);
printf("Struct string: %s\n", string2->str);
free(string2);
结果是:
结构字符串:helloWorld
结构字符串:ÉÉÉÉÉï Uï∞â∞¶SVWh♦☺
结构字符串:另一个语句...
结构字符串:ÉÉÉÉÉï Uï∞â∞¶SVWh♦☺
感谢您的帮助。
[感谢所有更新]
这是完整的工作代码。已解决。谢谢你们。
结构字符串项 {
国际化;
字符 str[1];
};
void allocationStringBuffer (char* stringContent, struct stringItem** pstring) {
// 动态大小的对象
诠释n;
n = strlen(字符串内容);
结构字符串项目*字符串;
字符串 = malloc(sizeof(struct stringItem) + (n+1));
if (string == NULL) { // 检查 malloc 是否成功
printf("字符串内存分配失败。\n");
// 退出(-1);
}
strcpy(string->str, stringContent);
printf("结构字符串:%s\n", string->str);
字符串->len = n;
*pstring = 字符串;// 将分配的指针复制到输出参数。
}
主要是
结构字符串项目 *string2;
allocationStringBuffer ("helloWorld", &string2);
printf("结构字符串:%s\n", (*string2).str);
免费(字符串2);
allocationStringBuffer("另一个语句...", &string2);
printf("结构字符串:%s\n", string2->str);
免费(字符串2);