0

I am trying to assign a string to a pointer which is in the structure. Even though, I am able to initialise the string to pointer successfully, when I try to use the string(access the pointer), I get some random values. How should I solve the problem. Following is my code:

typedef struct
{

    uint8_t LOG_ID;
    uint8_t timestamp;
    uint8_t loglength;
    uint8_t checksum;
    uint8_t *payload;

} Log;
Log LB_t;

void main(){
LB_t.LOG_ID=1;
    LB_t.timestamp=3;
    LB_t.loglength=17;
    LB_t.checksum=89;

LB_t.payload="LED initialised";
log_item(&LB_t,17);
}
void log_item(uint8_t *logptr,uint8_t length){
    while(length!=0){
    CB_buffer_add_item(tx,*logptr);
    length=length-1;
logptr++;
    }
}

Is there any alternate way in which I can access the pointer?

5
  • main() returns int. uint8_t is not guaranteed to exist, nor to be compatible with char (i.e. a "string"). Please format your code properly if you expect others to read it. And please provide examples of input and output data. Commented Dec 1, 2017 at 16:48
  • why is payload not char*. Why is log_item arg not of type Log? What is CB_buffer_add_item Commented Dec 1, 2017 at 16:49
  • @underscore_d This looks like it could be embedded, in which case void main() is OK. Commented Dec 1, 2017 at 16:49
  • Where do you try to access the string? It looks like you're trying to manually reinvent the wheel of offsetof(). Is that right? It usually doesn't end well for people who try it. Commented Dec 1, 2017 at 16:53
  • Why do you pass 17? Commented Dec 1, 2017 at 17:13

1 Answer 1

1

OK, I get it , you expect 'payload' to be inside the struct. Its not, just the pointer. You need to do this

typedef struct
{

    uint8_t LOG_ID;
    uint8_t timestamp;
    uint8_t loglength;
    uint8_t checksum;
    uint8_t payload[100];

} Log;

and then

strncpy(LB_t.payload, "LED initialised", 100);

you probaly want to make the 100 a const or #define somehwere. And change yr 17 to sizeof(Log)

Sign up to request clarification or add additional context in comments.

3 Comments

is there any way apart from string copy function to do the above operation, beacause I am not allowed to use string.h library
use memcpy or write your own strncpy function that loops over the character array one byte at a time
payload should be an array of char.

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.