Thread: assign values to string arrays

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    23

    assign values to string arrays

    Hi,

    I want to assign values to a string array, which is declared as char** stringArr, by reading a file. One line of the file is to be one element of the string array. My code is as the following:

    Code:
    char** stringArr;
    
    
    char* l     = malloc(MAX_CHAR); //MAX_CHAR is defined
    char** lp = stringArr;
    
    int i = 0;
    while( fget(l, MAX_CHAR, fp ) != NULL ){ //fp is the pointer to a opened file
         *lp++ = l;
          i++;
    }
    After that, when I checked the content of stringArr as the following, there are errors.

    Code:
    int j;
    for ( j = 0; j < i; j++ ){
         printf("%s", *stringArr[j]);
    }
    Just quite confused what goes wrong here?

    Many thanks!

    Regards,
    Paul
    Last edited by paulur; 03-21-2006 at 03:34 PM.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You are only allocating one string.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Mar 2006
    Posts
    23
    Yeh, that really is the reason casued the error!

    But I just can't understand why it likes that. because both stringArr and l are char**....

    Many thanks!

    Paul

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    Code:
    char** stringArr = malloc ( MAX_LINES * sizeof *stringArr );
    for ( i = 0 ; i < MAX_LINES ; i++ ) stringArr[i] = malloc ( MAX_CHARS * sizeof *stringArr[i] );
    Now you can read in MAX_LINES
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  3. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  4. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM