Search code examples
cfiletypescharformat-specifiers

What format specifier should I use here?


Got this code right here to print out the name of an opened file (its a height map in case you were wondering) and every time I try to print out I get format warnings, which format specifier should I use for this?

    unsigned char* data = stbi_load("textures/height.png", &width, &height, &nr_components, 0);
    printf("Loaded file: %u\n", data);

Solution

  • If your goal is to print the address where the data was loaded, that would be %p:

    printf("Loaded file: %p\n", (void*)data);
    

    If you want to print the actual data, byte by byte, you should loop over the bytes and use %hhu (for decimal) or %hhx (for hexadecimal):

    printf("Loaded file:\n");
    for(int i = 0; i < width*height*nr_components; ++i)
        printf("%hhx ", data[i]);
    printf("\n");
    

    data doesn't contain the name of the file though, so if you want to print just the name, then print that same string that you passed to stbi_load:

    const char *filename = "textures/height.png";
    unsigned char* data = stbi_load(filename, &width, &height, &nr_components, 0);
    printf("Loaded file: %s\n", filename);