Question

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).

Was it helpful?

Solution

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).

OTHER TIPS

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]);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top