1
#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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Hakan
  • 97
  • 1
  • 10

2 Answers2

3

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.
Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Thanks Sourav, can you edit my codes and show us? Because I didn't understand your first statement completely. I'm trying to learn more English. – Hakan Aug 21 '15 at 07:17
  • It gives "error C4700: uninitialized local variable 'ptrArray' used". – Hakan Aug 21 '15 at 07:42
2

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.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115