简体   繁体   English

为什么我的结构在打印内容后消失了?

[英]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). 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). The project is to do simple queue with type given by user and the problem is with the following code:该项目是用用户给定的类型做简单的队列,问题在于以下代码:

#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] );
}

When I allocate usertype it works well and the pItem is created as expected, but after I printf it it's seemes like pItem is no longer there and there's just garbage nKey number and there isn't any tab.当我分配用户类型时,它运行良好并且 pItem 按预期创建,但是在我 printf 之后,它似乎 pItem 不再存在并且只有垃圾 nKey 编号并且没有任何选项卡。

Is this problem because im allocating this data struct in memory wrongly and somehow t as a local variable for AllocateUsertype disapears at random moment?这个问题是因为我在 memory 中错误地分配了这个数据结构,并且不知何故,作为 AllocateUsertype 的局部变量在随机时刻消失了吗? If yes can someone give me idea how to do it correctly?如果是的话,有人可以告诉我如何正确地做到这一点吗?

As pointed out in the comments, the problem is that inside AllocateUsertype() you are returning a pointer to a local variable that won't exists anymore once the function returns.正如评论中所指出的,问题在于,在AllocateUsertype()内部,您正在返回一个指向局部变量的指针,一旦 function 返回,该变量将不再存在。

The solution is to allocate a Usertype using malloc , just like you did for t , and then return its pointer.解决方案是使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM