Domanda

I am trying assign byte values of 0x00 to 0xff to a C string with a function, and also report a length of the generated string. I am trying to get headed in the right direction, but seem to be stuck on a rather frustrating problem.

The code below shows my attempt to load byte values into the variable (passed by reference) charset. The code compiles and runs, but outputs nothing. However if I uncomment the second line in the loadCharset for loop, it will print all the desired values. I seem to be missing something on how to assign these values to the C string.

int loadCharset(int setname, char charset[], int *setlen){ //string sName){
    for (int i = 0x00; i <= 0xff; i++){
        charset[i] = i;
        // printf("%c", i);
    }
    // *setlen = 256;
}

int main() {
    char charset[256];
    int* setlen;
    loadCharset(1, charset, setlen);
    printf("%s", charset); // yields no output
}
È stato utile?

Soluzione

The first element of the charset array is 0x00, which is the string terminator, telling printf to stop there -- without printing anything. Replace printf with:

fwrite(charset, sizeof (charset), 1, stdout);

which allows you specify the lenght of the array being printed explicitly.

Altri suggerimenti

Anticipating your next question:

As soon as you uncomment // *setlen = 256; you will run into trouble.

This is what you want :

int main() {
    char charset[256];
    int setlen;
    loadCharset(1, charset, &setlen);
    printf("%s", charset); // yields no output
}

Note the & before setlen. And there is no more * before setlen in the declaration.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top