how can i convert a void array to unsigned char array?
could you plz give a little sample?

Dani AI

Generated

: quick clarification first — C has no "void array". You likely have a void * buffer (for example from malloc, a function argument, or a read) and you want to treat it as a sequence of bytes. The usual approach is to cast that pointer to unsigned char * for byte-wise access. That cast does not copy memory; it only changes how you index the bytes. If you need a separate unsigned char buffer, allocate one and copy with memcpy.

Here is a minimal example showing safe byte access and an explicit copy:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    void *buf = malloc(6);
    if (!buf) return 1;
    memcpy(buf, "Hi!\n", 4); /* sample data, length must be known */
    unsigned char *bytes = (unsigned char *)buf;
    for (size_t i = 0; i < 4; ++i)
        printf("%02x ", bytes[i]);
    putchar('\n');
    /* make a separate unsigned-char copy if you need ownership */
    unsigned char *copy = malloc(4);
    memcpy(copy, bytes, 4);
    free(copy);
    free(buf);
    return 0;
}

Notes and cautions: const matters — if you start with const void *, cast to const unsigned char *. ISO C does not allow pointer arithmetic on void * (some compilers accept it as an extension), so cast before indexing. Using unsigned char to read object bytes is allowed by the C aliasing rules (it is the defined way to inspect object representations). Do not treat binary data as a C string — %s expects a NUL-terminated char * and will read past bounds. If you need to interpret multi-byte integral values from the byte buffer, use memcpy into a suitably typed variable to avoid alignment and strict-aliasing issues.

As demonstrated, casting to char * works for strings; for raw bytes prefer unsigned char *. As suggested, include a short code snippet of what you have if further help is needed.

Recommended Answers

All 2 Replies

could not understand your question. Did you declared a void pointer and then allocated memory? I mean if you could post some code snippet what you want to do, i can try to answer.

#include <stdio.h>
void foo(void *);
int main()
{
    char str[] = "This is a tes";
    
    foo(str);
    
    getchar();
    return 0;
}
void foo(void *str)
{
     printf("%s",(char*)str);
}
/* my output
This is a tes
*/

ssharish2005

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.