[英]Why does my struct disapear after printing it's content?
I'am working on a project for my programming class (teoretically in C++ but our professor isn't big fan of C++ solutions and C is better viewed by him). 該項目是用用戶給定的類型做簡單的隊列,問題在於以下代碼:
#include <cstdlib>
#include <cstring>
#include <stdio.h>
typedef struct
{
int nKey;
int* pTab;
}Usertype;
Usertype* AllocateUsertype( );
void PrintUsertype( Usertype* pItem );
int main()
{
Usertype *pItem = AllocateUsertype();
printf( "nKey: %d, pTab: %d %d", pItem->nKey, pItem->pTab[0], pItem->pTab[1] );
pItem->nKey = 3;
PrintUsertype( pItem );
}
Usertype* AllocateUsertype( )
{
Usertype* pItem = NULL;
int* t = NULL;
t = (int*)malloc( 2*sizeof( int ) );
if( !t ) return NULL;
memset( t, 0, 2*sizeof( int ) );
Usertype Item = { 0,t };
pItem = &Item;
return pItem;
}
void PrintUsertype( Usertype* pItem )
{
printf( "nKey: %d, pTab: %d %d", pItem->nKey, pItem->pTab[0], pItem->pTab[1] );
}
當我分配用戶類型時,它運行良好並且 pItem 按預期創建,但是在我 printf 之后,它似乎 pItem 不再存在並且只有垃圾 nKey 編號並且沒有任何選項卡。
這個問題是因為我在 memory 中錯誤地分配了這個數據結構,並且不知何故,作為 AllocateUsertype 的局部變量在隨機時刻消失了嗎? 如果是的話,有人可以告訴我如何正確地做到這一點嗎?
正如評論中所指出的,問題在於,在AllocateUsertype()
內部,您正在返回一個指向局部變量的指針,一旦 function 返回,該變量將不再存在。
解決方案是使用Usertype
分配用戶malloc
,就像您為t
所做的那樣,然后返回其指針。
Usertype* AllocateUsertype( )
{
Usertype* pItem = NULL;
pItem = (Usertype*)malloc(sizeof(Usertype));
if (!pItem) return NULL;
int* t = NULL;
t = (int*)malloc( 2*sizeof( int ) );
if( !t ) return NULL;
memset( t, 0, 2*sizeof( int ) );
pItem->nKey = 0;
pItem->pTab = t;
return pItem;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.