3

I have struct like this

struct tag{ char *pData};

I want to fill this element (pData) in loop.

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

Help me please guys.

1
  • It is unclear what you are going to do with the pointer. Commented Aug 12, 2015 at 10:43

3 Answers 3

2

First of all your pData must point to some valid buffer if it points to some valid buffer you can fill it just like that.

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

If you want to copy this same value all over the buffer which I doubt (however your code implies that) just use memset standard library function for this purpose.

Please specify on the example what do you want to happen to this buffer and give more context of your use case. It looks like you are beginner and you might need a little bit more help than you asked in order to make your program fine.

Here you have working code example for sth I think you want but you don't know how to ask about it.

#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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

In case you dont trying to set the pData offset, try to use * operator like this:

*(myTag.pData) = number;

UPDATE this in case you want only fill one value in your tag, if you want to copy the whole array see the other answer.

Comments

0

Because pData is a char * without any space allocated for the data, if you don't need to preserve the contents of array newData, you can simply assign to the pointer:

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

Or alternatively create another array fill it then assign to the pointer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.