creating a dynamically allocated array of strings from a file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gucci09
    New Member
    • Mar 2007
    • 20

    creating a dynamically allocated array of strings from a file

    I was wondering how you would go about creating a dynamically allocated array of strings from a file. i have a dictionary that i want to load in my program in order to spell check. i cant decide if it is best to use an array of string pointers or an array of the actual words. also i am very new to C and really am not comfortable with malloc yet. any help would be greatly appreciated
  • Silent1Mezzo
    New Member
    • Feb 2007
    • 208

    #2
    Originally posted by gucci09
    I was wondering how you would go about creating a dynamically allocated array of strings from a file. i have a dictionary that i want to load in my program in order to spell check. i cant decide if it is best to use an array of string pointers or an array of the actual words. also i am very new to C and really am not comfortable with malloc yet. any help would be greatly appreciated
    Unfortunately in C there is no really easy way of doing this. The easiest way I can think of off the top of my head is to have a double pointer.

    [code=c]char **ptr;[/code]

    I would get really comfortable with malloc because you're going to be using it alot. Since the size of the string can fluctuate and you want a dynamic number of these strings you basically need to have a double pointer.

    Comment

    • gucci09
      New Member
      • Mar 2007
      • 20

      #3
      thanks for the suggestion. so if i was going to use a double pointer would i malloc space for the rows and columns separately or can you do it together? again im not good with malloc. also i am trying to read this dictionary from one that is already on my system. so how would i determine how big to malloc space based on how many words are in this dictionary. i would just go look at it but my boss's dictionary might be different because he has an older version of ubuntu. so ya i guess would also be helpful to know to be able to put this dictionary in this program.

      Comment

      • Silent1Mezzo
        New Member
        • Feb 2007
        • 208

        #4
        Originally posted by gucci09
        thanks for the suggestion. so if i was going to use a double pointer would i malloc space for the rows and columns separately or can you do it together? again im not good with malloc. also i am trying to read this dictionary from one that is already on my system. so how would i determine how big to malloc space based on how many words are in this dictionary. i would just go look at it but my boss's dictionary might be different because he has an older version of ubuntu. so ya i guess would also be helpful to know to be able to put this dictionary in this program.
        I'm not that great with pointers but I believe you have to do something like this

        [code=c]
        char **ptr;
        *ptr = malloc(sizeof(p tr) + 1);
        ptr = malloc(sizeof(d ictionaryLine) + 1);
        [/code]

        Basically you allocate room for one more line and then you malloc room for the length of the line.

        Comment

        • gucci09
          New Member
          • Mar 2007
          • 20

          #5
          cool thanks. so is that for just one line? like say the dictionary has 40000 words in it. but i really dont know how many there are. how do i check for the amount of lines/words/strings the dictionary contains inorder to put that in my malloc. like can i loop to the end of the file and count them or how do i do that. this is the first time ive been asked to program something that opens other files and such.

          Comment

          • ilikepython
            Recognized Expert Contributor
            • Feb 2007
            • 844

            #6
            Originally posted by Silent1Mezzo
            I'm not that great with pointers but I believe you have to do something like this

            [code=c]
            char **ptr;
            *ptr = malloc(sizeof(p tr) + 1);
            ptr = malloc(sizeof(d ictionaryLine) + 1);
            [/code]

            Basically you allocate room for one more line and then you malloc room for the length of the line.
            I don't think that's correct.
            I believe it is like this:
            [code=c]
            char **ptr;
            ptr = malloc(rows * sizeof(int *));
            for (int x = 0; x < rows; x++)
            {
            ptr[x] = malloc(columns * sizeof(int))
            }
            [/code]

            Comment

            • Savage
              Recognized Expert Top Contributor
              • Feb 2007
              • 1759

              #7
              Originally posted by ilikepython
              I don't think that's correct.
              I believe it is like this:
              [code=c]
              char **ptr;
              ptr = malloc(rows * sizeof(int *));
              for (int x = 0; x < rows; x++)
              {
              ptr[x] = malloc(columns * sizeof(int))
              }
              [/code]
              ilikepython is correct except that he forgot to cast them to char pointers.Rememe ber:

              void *malloc(size_t size);

              this is malloc declararation.

              So it should be:

              [code=c]
              char **ptr;
              ptr = (char**)malloc( rows * sizeof(int *));
              for (int x = 0; x < rows; x++)
              {
              ptr[x] = (char*)malloc(c olumns * sizeof(int))
              }
              [/code]

              Savage

              Comment

              • gucci09
                New Member
                • Mar 2007
                • 20

                #8
                hey thanks you guys...but how do i know how big the rows and columns are based on the dictionary file i have?

                Comment

                • Savage
                  Recognized Expert Top Contributor
                  • Feb 2007
                  • 1759

                  #9
                  Originally posted by gucci09
                  hey thanks you guys...but how do i know how big the rows and columns are based on the dictionary file i have?
                  Well you have a file after all.How do you read data from file?You could just add a variable that will count how many lines is there in file and then that would be rows,for columns there are two options:

                  1.Build another dynamilcy array that will keep track of the everyline length

                  2.Find the longest line and make every column of same size

                  Savage

                  Comment

                  • gucci09
                    New Member
                    • Mar 2007
                    • 20

                    #10
                    see i guess that is my question though. maybe i am dumb but i dont know how to count lines in a file. like i guess i could make a variable called 'counter' but how do i increment that so it skips a line. i hope i dont sound too retarded but i really am new to this and my boss wants this done soon. as you can see i am working on it from home now just so i can see if i can get it done.

                    Comment

                    • Savage
                      Recognized Expert Top Contributor
                      • Feb 2007
                      • 1759

                      #11
                      Originally posted by gucci09
                      see i guess that is my question though. maybe i am dumb but i dont know how to count lines in a file. like i guess i could make a variable called 'counter' but how do i increment that so it skips a line. i hope i dont sound too retarded but i really am new to this and my boss wants this done soon. as you can see i am working on it from home now just so i can see if i can get it done.
                      You are reading in a line using fgets(),right?

                      So u have a while loop with condition:

                      !feof(FILE *pointer) or something like this

                      every time that fgets makes a read,you increase your row counter


                      Savage

                      Comment

                      • gucci09
                        New Member
                        • Mar 2007
                        • 20

                        #12
                        so i am still having the same problem. here is my code. i keep getting a seg fault.


                        Code:
                        s=(char **)malloc(1*sizeof(char*));
                        		s[0]=(char *)malloc(strlen(s[i]));
                        				
                        		i++;
                        		
                        
                        	while(!feof(finptr)){
                        		s=(char **)realloc(s,i*sizeof(char*));
                        		s[i]=(char *)realloc(s[i],strlen(s[i]));	
                        	}

                        Comment

                        • Savage
                          Recognized Expert Top Contributor
                          • Feb 2007
                          • 1759

                          #13
                          Originally posted by gucci09
                          so i am still having the same problem. here is my code. i keep getting a seg fault.


                          Code:
                          s=(char **)malloc(1*sizeof(char*));
                          		s[0]=(char *)malloc(strlen(s[i]));
                          				
                          		i++;
                          		
                          
                          	while(!feof(finptr)){
                          		s=(char **)realloc(s,i*sizeof(char*));
                          		s[i]=(char *)realloc(s[i],strlen(s[i]));	
                          	}

                          Have you freed the memory?

                          Savage

                          Comment

                          • gucci09
                            New Member
                            • Mar 2007
                            • 20

                            #14
                            i free it at the end of my program i just copied a part of it. but now when i go thru the code it only lets me copy 3 words into my 's' string. once i=3 then it seg faults. i dunno whats going on. ill copy the whole code this time.


                            Code:
                            #include <stdio.h>
                            #include <stdlib.h>
                            #include <string.h>
                            
                            
                            int main(int argc, char *argv[]){
                            
                            	FILE *finptr;		//file pointer to input file
                            
                            	int i=0;		//for incrementing
                            	int loweraddress;	//lower address of file stored in array
                            	int upperaddress;	//upper address of file stored in array
                            	int counter=0;		//counts how many strings in file	
                            	char **s;		//pointer to character sting
                            	char hold[]="Conspiracy Theory's are cool!";
                            	
                            
                            /*-------------------------------------------------------------------------------*/
                            //test for too few arguements	
                            	if(argc<2){
                            		printf("\nToo few arguements \n");
                            		printf("Usage: <program> <input file> \n");
                            		return 0;
                            	}
                            
                            //test for too many arguements
                            	if(argc>2){
                            		printf("\nToo many arguements \n");
                            		printf("Usage: <program> <input file> \n");
                            		return 0;
                            	}
                            
                            //test to see if input file can be opened and open it
                            	if((finptr=fopen(argv[1],"rt"))==NULL){
                            		printf("\n Cannot open input file \n");
                            		return 0;
                            			
                            	}
                            
                            //malloc array and copy in words
                            
                            		if((s=(char **)malloc(1*sizeof(char*)))==NULL){
                            			printf("malloc failed\n");
                            		}
                            		fgets(hold,100,finptr);
                            		s[i]=(char *)malloc(strlen(hold));
                            		strcpy(s[i],hold);
                            		printf("%s \n",s[i]);
                            		
                            				
                            		i++;
                            		
                            
                            	while(!feof(finptr)){
                            		if((s=(char **)realloc(s,i*sizeof(char*)))==NULL){
                            			printf("malloc failed \n");
                            		}
                            		fgets(hold,100,finptr);
                            		s[i]=(char *)realloc(s[i],i*strlen(hold));
                            		strcpy(s[i],hold);
                            		printf("%s \n",s[i]);
                            		i++;
                            		
                            			
                            	}
                            
                            	printf("%d - %d \n", &s[0], &s[i]);
                            /*----------------------------------------------------------------------------------*/
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            free(s);
                            return 0;
                            }

                            Comment

                            • Savage
                              Recognized Expert Top Contributor
                              • Feb 2007
                              • 1759

                              #15
                              With this line here,you allocate only enough memory for 4 char *:
                              [CODE=c]
                              if((s=(char **)malloc(1*siz eof(char*)))==N ULL){[/CODE]

                              Sizeof char* is 4,so when i goes over 3...seg error.

                              You will need to check first the file length and then allocate memory

                              Savage

                              Comment

                              Working...