简体   繁体   中英

How to use fprintf with a dynamically allocated unsigned char* array in C

I'm trying to write a unsigned char* array to a file.

A minimal working example of the code that I've tried so far is (assume fp is correctly initialised):

unsigned char* x; int i; int j; int sizeOfx;
for (i=0; i<n; i++) {
    x = // getter function with parameter i
    sizeOfx = // getter function that returns the number of elements in x
    for (j=0; j<sizeOfx; j++) {
        fprintf(fp,"%s",x[j]);
    }
}

ie I'm going through the char array one element at a time and writing it to the file.

However, I get the error

format ‘%s’ expects argument of type ‘char*’, but argument 3 has type ‘int’ [-Wformat]

How can I fix this?

Thank you very much in advance!

Try %c (for character printing) instead of %s.

Alternatively you could write the print line as follows:

fprintf(fp,"%s",(char*)x[j]);

which statically casts that pointer at x[j] back to a string (essentially), then if the string coming into that loop were "abcdef", then the output would be as follows:

"abcdefbcdefcdefdefeff"

This is where c is completely open to do what you want to do.

%s is used to print a string, so you would need to change x[j] to x to 'fix' your error.

As you really seem to want to write each char separately, you need to think how you want to store the 'elements' (characters of the string).

You can use %c to store their value as an ASCII value in the file (which is basically identical when using %s and x , unless you want to write more/less than the complete string).

Or you can store the 'element values' as integers, ie textual values using the characters 0-9, using %d . Or maybe hexadecimal using %x using the characters 0-9 and af.

So it is up to you how you want to store the 'elements' of x .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM