我有这样的结构
struct tag{ char *pData};
我想在循环中填充这个元素(pData)。
for(i=0; i<MAX; i++){
myTag.pData = newData[i]; // question is here!
}
请帮帮我。
最佳答案
首先,您的pData 必须指向某个有效的缓冲区,如果它指向某个有效的缓冲区,您就可以像那样填充它。
for(i=0; i<MAX; i++) {
// Note that newData must be this same type or you have
// to truncate whatever type you are writing there to char.
myTag.pData[i] = newData[i];
}
如果你想在整个缓冲区中复制相同的值,我怀疑(但是你的代码暗示)只需为此目的使用 memset 标准库函数。
请在示例中说明您希望此缓冲区发生什么,并提供您的用例的更多上下文。看起来您是初学者,您可能需要比您要求的更多的帮助才能使您的程序正常运行。
这里有工作代码示例,我想你想要,但你不知道如何询问它。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct tag{ char *pData; };
int main(void) {
int i;
struct tag myTag;
myTag.pData = (char*)malloc(10*sizeof(char));
if(NULL == myTag.pData) {
return 0;
}
const char *test = "Hello";
for(i=0; i<strlen(test); i++) {
myTag.pData[i] = test[i];
}
// Put null termination at the end of string.
myTag.pData[i] = '\0';
printf("%s", myTag.pData);
free(myTag.pData);
return 0;
}
关于c - 如何在C中用数组填充结构的指针元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31962302/