Domanda

An example says more than thousand words:

unsigned char *hello = (unsigned char*)malloc(STR_LEN * sizeof(unsigned char));
const char *str= "haha";
memcpy(hello, str, strlen(str) + 1);

How can I print the content of the whole hello-variable (printf("%s",..) would only respect the part before the \0-termination and not all STR_LEN characters).

È stato utile?

Soluzione

You can use fwrite to write unformatted data:

char buf[4] = { 1, 2 };

fwrite(buf, 1, 4, stdout);   // writes the bytes 1, 2, 0, 0

You could use fwrite(hello, 1, STR_LEN, stdout), but note that you're not allowed to read uninitialized data (so you should use calloc instead or initialize the data in some other way).

Altri suggerimenti

You'd have to write your own for loop that goes from hello to hello+STR_LEN, and prints each character one at a time.

for (unsigned char *c = hello, e = hello +STR_LEN; c < e; ++c) {
    printf("%c", *c);
}
int i;
for(i = 0; i < STR_LEN; i++) {
    putchar(hello[i]);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top