Hakan
Hakan

Reputation: 109

How to send 2D char pointer to a function for memory allocation?

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


void createDynamicArrayForChar(int dimension, char **ptr)
{
    ptr = (char**)malloc(dimension*sizeof(char*));

    for (int i = 0; i < dimension; i++)
    {
        ptr[i] = (char*)malloc(20 * sizeof(char));
        ptr[i] = "value";
    }
}

int main()
{
    char **ptrArray;
    createDynamicArrayForChar(5, ptrArray);
    printf("%s", ptrArray[3]);


    getchar(); getchar();
    return 0;
}

It gives some errors when I try to compile this codes. How can I solve this problem? How to send 2D char pointer to a function in C?

Upvotes: 1

Views: 60

Answers (2)

Jabberwocky
Jabberwocky

Reputation: 50883

You probably need this (no error checking and not debugged code):

void createDynamicArrayForChar(int dimension, char ***ptr)
{
    *ptr = (char**)malloc(dimension*sizeof(char*));

    for (int i = 0; i < dimension; i++)
    {
        (*ptr)[i] = (char*)malloc(20 * sizeof(char));
        strcpy((*ptr)[i],"value");
    }
}

or

char **createDynamicArrayForChar(int dimension)
{
    char **ptr = (char**)malloc(dimension*sizeof(char*));

    for (int i = 0; i < dimension; i++)
    {
        ptr[i] = (char*)malloc(20 * sizeof(char));
        strcpy(ptr[i],"value");
    }

    return ptr;
}

int main()
{
    char **ptrArray;
    ptrArray = createDynamicArrayForChar(5);
    ...

Read also Sourav Ghosh's answer.

Upvotes: 2

Sourav Ghosh
Sourav Ghosh

Reputation: 134376

Firstly, as per the present code, I see two issues.

  1. You're passing ptrArray to the function and trying to allocate memory inside the function. Please be aware, C uses pass by value for function argument passing, so, if you want to allocate memory to ptrArray and expect that to be refeclted back to the caller, without returning, you'll be needing to pass a pointer to that `ptrArray.

  2. in the code

    ptr[i] = (char*)malloc(20 * sizeof(char));
    ptr[i] = "value";
    

    You're leaking memory. Once you've allocated memory using malloc(), you should use strcpy() to copy the data into the allocated memory.

That said, some advice:

  1. Please see why not to cast the return value of malloc() and family in C.
  2. sizeof(char) is guaranteed to be 1 in C. Using that as a multiplier is not required.
  3. Always check the success of malloc() before using the returned pointer.

Upvotes: 3

Related Questions