我想知道str指向的文字字串在哪里分配,因為(我假設)malloc 只為指向堆的指標騰出空間。
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int a;
char* str;
} Bar;
int main(int argc, char *argv[])
{
Bar* bar_ptr = (Bar*)malloc(sizeof(*bar_ptr));
bar_ptr->a = 51;
bar_ptr->str = "hello world!";
printf("%d\n", bar_ptr->a);
printf("%s\n", bar_ptr->str);
free(bar_ptr);
return 0;
}
uj5u.com熱心網友回復:
正確 - 您所有的結構型別存盤都是字串中第一個字符的地址。字串內容存盤在“其他地方” - 在字串文字中,在另一個動態分配的塊中,在一個static或auto陣列中等。
你可以宣告一切auto:
void foo( void )
{
char aStr[] = "this is not a test";
Bar barInstance;
barInstance.a = 51;
barInstance.str = aStr;
...
}
您可以動態分配所有內容:
Bar *barInstance = malloc( sizeof *barInstance );
if ( barInstance )
{
size_t size = strlen( "This is not a test" );
barInstance->str = malloc( size 1 );
if ( barInstance->str )
strcpy ( barInstance->str, "This is not a test" );
...
/**
* You must free barInstance->str before freeing
* barInstance - just freeing barInstance won't
* free the memory barInstance->str points to,
* since that was a separate allocation.
*/
free( barInstance->str );
free( barInstance );
}
** 編輯 **
還有其他可能性,但重點是字串本身與結構實體分開存盤。
uj5u.com熱心網友回復:
正如已經指出的,字串存盤在只讀資料段中。您可以列印存盤字串的地址(以十六進制格式),如下所示:
printf("0x%p\n", bar_ptr->str);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/532235.html
標籤:C结构动态内存分配
上一篇:使用calloc賦值
