次から文字列出力を取得していません。
構造体 stringItem {
int レン;
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);
結果は次のとおりです。
構造文字列: helloWorld
構造体文字列: ÉÉÉÉÉï Uï∞â∞¶SVWh♦☺
構造体文字列: 別のステートメント...
構造体文字列: ÉÉÉÉÉï Uï∞â∞¶SVWh♦☺
ご協力ありがとうございました。
[ALLのおかげで更新]
これが完全な作業コードです。解決済みです。皆さんありがとうございます。
構造体 stringItem {
int レン;
char str[1];
};
void allocationStringBuffer (char* stringContent, struct stringItem** pstring) {
// 動的サイズのオブジェクト
int n;
n = strlen(stringContent);
struct stringItem *string;
string = malloc(sizeof(struct stringItem) + (n+1));
if (string == NULL) { // malloc が成功したかどうかを確認します
printf("文字列のメモリ割り当てに失敗しました。\n");
// 終了(-1);
}
strcpy(string->str, stringContent);
printf("構造体文字列: %s\n", string->str);
string->len = n;
*pstring = 文字列; // 割り当てられたポインタを出力パラメータにコピーします。
}
主に
struct stringItem *string2;
allocationStringBuffer ("helloWorld", &string2);
printf("構造体文字列: %s\n", (*string2).str);
無料 (文字列 2);
allocationStringBuffer ("別のステートメント...", &string2);
printf("構造体文字列: %s\n", string2->str);
無料 (文字列 2);