如何在C语言中使用数组填充结构体的指针元素

3
我有这样的结构体
struct tag{ char *pData};

我希望在循环中填充pData元素。

for(i=0; i<MAX; i++){
    myTag.pData = newData[i]; // question is here!
}

Help me please guys.


不清楚你打算用指针做什么。 - Vlad from Moscow
3个回答

2

首先,如果您的 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;
}

0
如果您不想尝试设置pData偏移量,请尝试使用*运算符,如下所示:
*(myTag.pData) = number;

更新:如果您只想在标签中填写一个值,那么请使用此方法。如果您想要复制整个数组,请参阅其他答案。


0

因为 pData 是一个未分配空间的 char *,如果你不需要保留数组 newData 的内容,可以直接将指针赋值:

char newData[10];
myTag.pData = newData;

或者创建另一个数组并填充它,然后将其分配给指针。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接