CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 24

Threaded View

  1. #19
    Join Date
    Jul 2005
    Posts
    266

    Re: allocating bidimensional matrix

    Well just for fun I decided to fix your reallocating issue and give you a few pointers ( hopefully valid ) First of all you have no need of the static variable and no need to save the length of strings because what you are reallocating is just an array of pointers to the malloced strings, you dont need to reallocate the strings just the array of pointers so all you need to save is count of elements inside which you already use the n parameter for :P Second mistake you have was the dereferencing of the list pointer , *list[n] which in fact dereferences list[n] but you actually need to dereference list and get its n-th element so a pair of brackets can be very useful here (*list)[n]. So the final code should look like this:
    Code:
    #include <iostream>
    using namespace std;
    
    
    void add(char ***list, int n, char *person)
    {
    *list=(char**)realloc(*list,(n+1)*sizeof(char**));
    (*list)[n] = (char*) malloc (strlen(person) + 1);
    strcpy((*list)[n], person);
    }
    
    int main()
    {
    char **list = NULL;
    int n = 0;
    
    add(&list, 0, "jack");
    printf("list[0]: &#37;s\n", list[0]);
    
    n++;
    
    add(&list, 1, "jeff");
    printf("list[1]: %s\n", list[1]);
    free(list[0]);
    free(list[1]);
    free(list);
    return 0;
    }
    Hope I helped
    Last edited by kolkoo; August 3rd, 2009 at 08:52 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured