Question

In the main method , i am creating an array of pointers to string in the add method i am reallocating the array size and adding x elements which i dont know while coming back to main how can i know the new size of the array , i mean the number of elements int the array ?

Here is my code .. (it has some bugs)

#include <stdio.h>

void add(char ***x);

int main()
{
  char **s;
  s = (char **) malloc(sizeof(char *));
  int i;
  add(&s);

  for( i=1;i<=?????(**find the new size of the array** );i++)
    puts(*s[i]);

  return 0;
}

void add(char ***x)
{

  - ** // alter arry add x random datas to the array of string pointer**

  /*
   s[1]="Hello";
   s[2]="Need";
   s[3]="a help";
   s[4]="and help";
   s[5]="for the  help";
   */

  char **data;
  int i = 0;
  for (i = 1; i <= 5; i++)
  {
    data = (char **) realloc(*x, 1 * sizeof(char *));
    data[i] = (char *) malloc(i * sizeof(char *));
    strcpy(data[i], "first");
  }

}

can some one please point and fix the bug in the code..

Was it helpful?

Solution

(Sidenote:

can some one please point and fix the bug in the code..

hey, isn't that what debuggers are for?)

Long story short, keep track of it manually:

char **func_that_reallocs(char **ptr, size_t *sz)
{
    char **tmp = realloc(ptr, new_size * sizeof(*ptr));
    *sz = new_size;
    return tmp;
}

And please do not cast the return value of malloc()!

OTHER TIPS

Always add one entry more to the array as needed and set this additional last entry to NULL.

Then write a function which scans the array until it find this NULL-pointer and return the number of entries counted up until then and you are done.

It's the same concept as for a C-"string", with the only difference of using a NULL instead of '\0' as (array-)terminator.

Some people call this last element also the "stopper"-element.

The positive thing about this approach is, one does not have to keep the array's size in a different variable, which might get out of sync with the real size of the array: The size is implicitly given by the array itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top