LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Problem of the sizeof() operator

Hello,

 

I have such a code phase:

 

static char data[]="Start to read";

 

int SaveLogData(char *data)
{
    FILE *fp;
    size_t len;
    
    len = sizeof(data)+1;
    
    fp = fopen("..\\log.dat", "a");
    fwrite(data, len*sizeof(char), 1, fp);
    fwrite("::", 3*sizeof(char), 1, fp);
    fwrite(DateStr(), 10*sizeof(char)+1, 1,fp);
    fclose(fp);

    return 0;
}

 

The compiling mode is in 64-bit, from the "log.dat" file, I can just see the part of the input string:"Start to r", I don't know why it will truncate some characters. Please advise how to avoid such a fault.

 

 

David

 

0 Kudos
Message 1 of 3
(3,293 Views)

Within your SaveLogData() function, you are re-defining data as a char*, instead of the original global static char[]. This causes the original array to become hidden, or out of scope, from the function. So the sizeof(data) operation within this function will return 8, which is the size of the 64 bit pointer you are passing to the function.

 

It is unwise to re-define variables in this way - it leads to confusion! Depending on your application, maybe you could use strlen(data) instead?

 

JR

Message 2 of 3
(3,265 Views)

Hi JR,

 

Yes , using the strlen() can resolve it. Thanks.

 

 

David

Message 3 of 3
(3,201 Views)