Results 1 to 10 of 10

Thread: [Resolved] Dynamic Array of Struct in C?

  1. #1

    Thread Starter
    Stuck in the 80s The Hobo's Avatar
    Join Date
    Jul 2001
    Location
    Michigan
    Posts
    7,256

    Resolved [Resolved] Dynamic Array of Struct in C?

    If I had this:

    Code:
    typedef struct {
        char *name;
        int age;
    } PersonalInfo;
    
    //...
    
    PersonalInfo *userInfos;
    
    userInfos = (PersonalInfo *) calloc(1, sizeof(PersonalInfo));
    How would I access the members of userInfos? I've tried many combinations with . and -> but nothing seems to work. Plenty of errors and crashes.
    Last edited by The Hobo; Oct 10th, 2005 at 10:40 AM.
    My evil laugh has a squeak in it.

    kristopherwilson.com

  2. #2
    Fanatic Member twanvl's Avatar
    Join Date
    Dec 2001
    Posts
    771

    Re: Dynamic Array of Struct in C?

    You can use it as an array:
    userInfos[0].name = ...;
    Or as a pointer:
    userInfos->name = ...;
    Both should work. Also, don't forget to free() your memory.

  3. #3
    Member
    Join Date
    Sep 2005
    Posts
    45

    Re: Dynamic Array of Struct in C?

    to access the pointer with in a struct use
    Code:
    struct -> pointerOfStruct;
    
    userInfos -> name;
    // in your case it would be
    to access simple members
    Code:
    struct.memberName;
    
    //in your case
    
    userInfos.age;




    [P.S]: please mark the post as resloved if you have your problem asnwered

  4. #4

    Thread Starter
    Stuck in the 80s The Hobo's Avatar
    Join Date
    Jul 2001
    Location
    Michigan
    Posts
    7,256

    Re: Dynamic Array of Struct in C?

    How would I allocate the char pointer in the struct?

    Code:
    userInfos[0].name = (char *) malloc ...
    strcpy(userInfos[0].name, nameVar);
    Crashes when I run it.
    My evil laugh has a squeak in it.

    kristopherwilson.com

  5. #5
    Fanatic Member twanvl's Avatar
    Join Date
    Dec 2001
    Posts
    771

    Re: Dynamic Array of Struct in C?

    are you sure the array you allocate is large enough? If you use strlen to determine the size you must add 1, because the string also stores a '\0' which is not counted by strlen:
    Code:
    char* mystring = malloc(strlen(input) + 1);
    strcpy(input, mystring);
    Also: Do you have to use C? C++ is much easier, especially for strings and arrays.

  6. #6

    Thread Starter
    Stuck in the 80s The Hobo's Avatar
    Join Date
    Jul 2001
    Location
    Michigan
    Posts
    7,256

    Re: Dynamic Array of Struct in C?

    Quote Originally Posted by twanvl
    are you sure the array you allocate is large enough? If you use strlen to determine the size you must add 1, because the string also stores a '\0' which is not counted by strlen:
    Code:
    char* mystring = malloc(strlen(input) + 1);
    strcpy(input, mystring);
    Also: Do you have to use C? C++ is much easier, especially for strings and arrays.
    I forgot to add 1, doh. And the class I'm doing this for is a C class...so...yeah, sadly. Don't get me started on my opinions on how the uni runs classes...
    My evil laugh has a squeak in it.

    kristopherwilson.com

  7. #7

    Thread Starter
    Stuck in the 80s The Hobo's Avatar
    Join Date
    Jul 2001
    Location
    Michigan
    Posts
    7,256

    Re: Dynamic Array of Struct in C?

    Okay, still not working:

    Code:
    #include <stdio.h>
    
    const int INITIAL_SIZE = 10;
    
    typedef struct {
    	char *word;
    	int count;
    } WordBank;
    
    main() {
    	// define local variables:
    	WordBank *words;
        char *word;
    	int c, currentWord = 0;
    
    	words = (WordBank *) calloc (INITIAL_SIZE, sizeof (WordBank));
    	word = (char *) calloc (25, sizeof (char));
    
        // get input:
        c = getchar();
        while (c != EOF) {
            // if the character is a space, replace it with \n
            if (isspace(c) || c == '\0') {
    	        words[currentWord].word = (char *) calloc (strlen(word) + 1, * sizeof(char));
    			strcpy(words[currentWord], word);
    
               // increment the word counter:
                currentWord++;
    
    			strcpy(word, "\0");
            // if the character is punctuation, replace it with null
    		} else if (ispunct(c)) {
                c = '\0';
    		} else {
    			//word = word + c;
    			strcat(word, &c);
    		}
    
            // grab the next character:
            c = getchar();
        }
    }
    The code is supposed to copy the input character by character, and each time a full word is found, it adds it to the array.

    With the standard example above (PersonalInfo), it works fine, but not in my real code (above)?
    My evil laugh has a squeak in it.

    kristopherwilson.com

  8. #8
    PowerPoster sunburnt's Avatar
    Join Date
    Feb 2001
    Location
    Boulder, Colorado
    Posts
    1,403

    Re: Dynamic Array of Struct in C?

    I made a couple changes, give this a try:


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    #include <string.h>
    const int INITIAL_SIZE = 10;
    
    typedef struct {
    	char *word;
    	int count;
    } WordBank;
    
    main() {
    	// define local variables:
    	WordBank *words;
        char *word;
    	int c, currentWord = 0;
    
    	words = (WordBank *) calloc (INITIAL_SIZE, sizeof (WordBank));
    	word = (char *) calloc (25, sizeof (char));
    
        // get input:
        c = getchar();
        while (c != EOF) {
            // if the character is a space, replace it with \n
            if (isspace(c) || c == '\0') {
    	        words[currentWord].word = (char *) calloc(strlen(word) + 1, sizeof(char));
    			strcpy(words[currentWord].word, word);
    
               // increment the word counter:
                currentWord++;
    
    			strcpy(word, "\0");
            // if the character is punctuation, replace it with null
    		} else if (ispunct(c)) {
                c = '\0';
    		} else {
    			//word = word + c;
    			strcat(word, (char*)&c);
    		}
    
            // grab the next character:
            c = getchar();
        }
    }
    Every passing hour brings the Solar System forty-three thousand miles closer to Globular Cluster M13 in Hercules -- and still there are some misfits who insist that there is no such thing as progress.

  9. #9

    Thread Starter
    Stuck in the 80s The Hobo's Avatar
    Join Date
    Jul 2001
    Location
    Michigan
    Posts
    7,256

    Re: Dynamic Array of Struct in C?

    Awesome, thanks. I don't know how that * got before sizeof(char). One more problem before I call this resolved:

    I'm supposed to let the size of the array grow after it reaches INITIAL_SIZE, but I'm screwing up the reallocation somehow. Any ideas?:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    #include <string.h>
    
    const int INITIAL_SIZE = 5;
    
    typedef struct {
    	char *word;
    	int count;
    } WordBank;
    
    main() {
    	// define local variables:
    	WordBank *words, *tmp;
        char *word;
    	int c, currentWord = 0;
        int i, index;
    
    	words = (WordBank *) calloc (INITIAL_SIZE, sizeof (WordBank));
    	word = (char *) calloc (25, sizeof (char));
    
        // get input:
        c = getchar();
        while (c != EOF) {
            // if the character is a space, replace it with \n
            if (isspace(c) || c == '\0') {
                if (currentWord > (INITIAL_SIZE - 1)) {
                    if ((tmp = realloc(words, sizeof(WordBank) * (currentWord))) == NULL) {
                        fprintf(stderr, "Reallocation failed.");
                    }
    
                    words = tmp;
                    free(tmp);
                }
    
                words[currentWord].word = (char *) calloc(strlen(word) + 1, sizeof(char));
                
                strcpy(words[currentWord].word, word);
                words[currentWord].count = 1;
    
                // increment the word counter:
                currentWord++;
    
                strcpy(word, "\0");
            // if the character is punctuation, replace it with null
    		} else if (ispunct(c)) {
                c = '\0';
    		} else {
    			//word = word + c;
    			strcat(word, (char*)&c);
    		}
    
            // grab the next character:
            c = getchar();
        }
    
        for (i = 0; i < currentWord; i++) {
            printf("%s\n", words[i].word);
        }
    
        free(words);
    }
    My evil laugh has a squeak in it.

    kristopherwilson.com

  10. #10

    Thread Starter
    Stuck in the 80s The Hobo's Avatar
    Join Date
    Jul 2001
    Location
    Michigan
    Posts
    7,256

    Re: Dynamic Array of Struct in C?

    Figured it out:

    Code:
    if ((tmp = realloc(words, sizeof(WordBank) * (currentWord + 1))) == NULL) {
    Thanks for the help, everyone.
    My evil laugh has a squeak in it.

    kristopherwilson.com

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