我没有得到以下字符串输出:
struct stringItem { int len; char 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);
结果是:
Struct string: helloWorld Struct string: ÉÉÉÉÉï Uï∞â∞¶SVWh♦☺ Struct string: another Statement... Struct string: ÉÉÉÉÉï Uï∞â∞¶SVWh♦☺感谢您的帮助。
[Updates with Thanks to ALL] Here is the full working code. It has been resolved. Thank you to ALL. struct stringItem { int len; char str[1]; }; void allocationStringBuffer (char* stringContent, struct stringItem** pstring) { // dynamically sized object int n; n = strlen(stringContent); struct stringItem *string; string = malloc(sizeof(struct stringItem) + (n+1)); 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; *pstring = string; // Copy allocated pointer to out-parameter. }在主目录
结构体 stringItem *string2; AllocationStringBuffer("helloWorld", &string2); printf("结构字符串: %s\n", (*string2).str); 自由(字符串2); allocateStringBuffer("另一条语句...", &string2); printf("结构字符串: %s\n", string2->str); 自由(字符串2); 前>
最佳答案
在我看来,您需要进行这些更改:
allocationStringBuffer ("helloWorld", &string2); // Pass ADDRESS of string2, not just string2
<小时/>
void allocationStringBuffer (char* stringContent, struct stringItem **pstring)
{
// dynamically sized object
int n;
n = strlen(stringContent);
struct stringItem* string; // Local variable, will be later copied to function parameter.
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;
*pstring = string; // Copy allocated pointer to out-parameter.
}
关于c - 无法正确访问结构体内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19687444/