如何使用calloc动态分配结构和它的TCHAR成员数组?

时间:2011-07-26 21:08:41

标签: dynamic-allocation

我可以在堆栈上设置足够简单的结构:

struct sArray
{
TCHAR sName[512];
};
struct sArray sKeys[2048] = {0};

但是这太占用了堆栈空间。

相反,我想把它全部放在堆上,所以我提出了这个:

struct sArray
{
    TCHAR *sName;
};
struct sArray *sKeys = (sArray *) calloc(2048, sizeof(sArray));

如何为sName动态分配内存?我试过这个并且它没有编译:

TCHAR *sKeys[0].sName = (TCHAR *) calloc(512,sizeof(TCHAR));

我真的在这里忽略了一些东西。有人可以帮忙吗?感谢。

2 个答案:

答案 0 :(得分:0)

只需使用

sKeys[0].sName = (TCHAR *) calloc(512,sizeof(TCHAR));

(前面没有TCHAR *)

答案 1 :(得分:0)

试试这个:

#include <stdlib.h>
#include <string.h>
#include <tchar.h>
#include <windows.h>
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
#include <Psapi.h>
#include <strsafe.h>
#include <cstring>

typedef struct MyData {
    TCHAR processPath[ 32 ];
} MYDATA, *PMYDATA;

int main()
{
    PMYDATA pData = (PMYDATA) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MYDATA));
    strcpy(pData->processPath, TEXT ("C:\\Windows\\System32\\notepad.exe")); 
}

我用这个命令编译:

"C:\MinGW64\bin\g++.exe" -o ThreadExample.exe ThreadExample.cpp -lpsapi