This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

malloc and two dimensional array ( char * * )

I want to allocate memory which I can use as a two dimensional array. But the following code is not working

unsigned char xdata ** memo;
unsigned char i = 0;
// n is number of rows
// size is number of columns
memo = (unsigned char xdata **) malloc( n*2 );
for ( ; i < size; i++)
	memo[i] = (unsigned char xdata *)malloc( size );
this code was inspired from
C++ new operator
memo = new char * [n];
for (int i=0; i < n; i++)
	memo[i*2] = new char [size];
Can you help me resolving this problem? Is there any problem with the logic?

PS: Fairly large memory has been allocated using init_mempool().

Parents
  • Technically, I need an array of pointers(char **)

    Do you need to allocate the array AND the stuff that the array objects point to? If so, then...

    Since you're using malloc to allocate the array of pointers, you need a pointer to the array:

    char xdata * xdata *PtrtoPtrs;

    You can allocate the table as follows:

    PtrtoPtrs = malloc (100 * sizeof (char xdata *));

    This allocates an array of 100 pointers.

    PtrToPtrs[0] is the first pointer in the table. PtrToPtrs[99] is the last (100th) pointer in the table.

    Once you allocate the table, you should probably clear the pointers to NULL.

    When you add items to the table, you'll need to malloc memory for those strings as well. For example:

    char buffer [50];  // contains string to add to table
    
    for (i=0; i<100; i++)
      {
      get_the_next_string(buffer);
      PtrToPtrs[i] = malloc(strlen(buffer)+1);
      if (PtrToPtrs[i] != NULL)
        strcpy (PtrToPtrs[i], Buffer);
      }
    

    Of course, you'll need to FREE the memory you stop using.

    Jon


    }

Reply
  • Technically, I need an array of pointers(char **)

    Do you need to allocate the array AND the stuff that the array objects point to? If so, then...

    Since you're using malloc to allocate the array of pointers, you need a pointer to the array:

    char xdata * xdata *PtrtoPtrs;

    You can allocate the table as follows:

    PtrtoPtrs = malloc (100 * sizeof (char xdata *));

    This allocates an array of 100 pointers.

    PtrToPtrs[0] is the first pointer in the table. PtrToPtrs[99] is the last (100th) pointer in the table.

    Once you allocate the table, you should probably clear the pointers to NULL.

    When you add items to the table, you'll need to malloc memory for those strings as well. For example:

    char buffer [50];  // contains string to add to table
    
    for (i=0; i<100; i++)
      {
      get_the_next_string(buffer);
      PtrToPtrs[i] = malloc(strlen(buffer)+1);
      if (PtrToPtrs[i] != NULL)
        strcpy (PtrToPtrs[i], Buffer);
      }
    

    Of course, you'll need to FREE the memory you stop using.

    Jon


    }

Children