[英]One TCHAR member in one C struct - how to dynamically allocate member and array of struct?
I have this struct: 我有这个结构:
struct sArray {
TCHAR *sName;
};
I want to now dynamically allocate memory for an array of sArray, and also dynamically allocate memory for sName. 我现在想为sArray数组动态分配内存,并且还为sName动态分配内存。 So I can use something like var[0].sName, var[1].sName...var[x].sName.
因此,我可以使用var [0] .sName,var [1] .sName ... var [x] .sName之类的名称。
I'm looking for a simple solution - tons of articles here and on the web about dynamic allocation, but none answer this. 我正在寻找一个简单的解决方案-此处和网络上有大量关于动态分配的文章,但没有人回答。
So, how do I do this? 那么,我该怎么做呢? And how do I free the member and array memory when done with them?
以及完成后如何释放成员和数组内存?
// +1 for the NULL terminal byte
TCHAR *names = (TCHAR *)calloc(1, (maxNameLen+1) * NumberOfNames);
struct sArray *array = (struct sArray *)malloc(numberOfArrays);
array[0].sName = names[0];
...
...
free(names);
free(array);
Try this: 尝试这个:
int len = 20; //number of elements (sArray's) you want in ar.
struct sArray *arr = malloc(length*sizeof(struct sArray));
int i;
int nameLength = 30; // max length of name
for (i = 0; i < length; ++i)
arr[i].sName = malloc(nameLength*sizeof(TCHAR));
and to free the memory: 并释放内存:
for (i = 0; i < length; ++i)
free(arr[i].sName);
free(arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.