0

The problem is as follows. I have a void pointer and I want to allocate string array with that. Is it possible to cast void* to char** like this:

void* ptr = (char**)calloc(size, sizeof(char*))

and then allocate each row of that table? I'm currently running out of ideas.

6
  • (1) I guess you didn't intend to make ptr have the type void. (2) There is a missing ). Commented Mar 11, 2018 at 13:12
  • Meta: Where is the line for yes/no question? Commented Mar 11, 2018 at 13:13
  • yes, you can. You do not need the (char**) cast.void* just points to any arbitrary chunk of memory. Commented Mar 11, 2018 at 13:14
  • If you want to allocate a "string array", if you want to allocate memory for the array and then for each row, it will be much easier if you work with a char **. Why do you want to use void * instead? Yu can do it, but it will be harder. Every time you do anything with ptr, you'll have to cast it back to char **. Commented Mar 11, 2018 at 13:15
  • I'd like to use that as a pointer to a dynamic array as well as a static array, depending on a value of a specific flag. Commented Mar 11, 2018 at 13:16

1 Answer 1

1

Psuedo Code that should get you what you need.

char **ptr = NULL;    
// Allocates an array of pointers
ptr = malloc(sizeof(char *) * (NUM_OF_STRINGS_IN_ARRAY));
If (ptr == NULL)
    return; // Do error handling here
for (int i =0; i < NUM_OF_STRINGS_IN_ARRAY; i++)
{
    // Allocates each string in the array.
    ptr[i] = malloc(strlen(STRING));
    if (ptr[i] == NULL)
    {
        return; // Do error handling here
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

He said he wanted ptr to be void *.
Actually, that's what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.