Reputation: 237
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.
Upvotes: 3
Views: 1868
Reputation: 1653
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;
}
Upvotes: 2
Reputation: 4877
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.
Upvotes: 0
Reputation: 89
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.
Upvotes: 0