473,396 Members | 1,756 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

creating a dynamically allocated array of strings from a file

20
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
Jun 13 '07 #1
16 3772
Silent1Mezzo
208 100+
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.

Expand|Select|Wrap|Line Numbers
  1. char **ptr;
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.
Jun 13 '07 #2
gucci09
20
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.
Jun 13 '07 #3
Silent1Mezzo
208 100+
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

Expand|Select|Wrap|Line Numbers
  1. char **ptr;
  2. *ptr = malloc(sizeof(ptr) + 1);
  3. ptr = malloc(sizeof(dictionaryLine) + 1);
  4.  
Basically you allocate room for one more line and then you malloc room for the length of the line.
Jun 13 '07 #4
gucci09
20
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.
Jun 13 '07 #5
ilikepython
844 Expert 512MB
I'm not that great with pointers but I believe you have to do something like this

Expand|Select|Wrap|Line Numbers
  1. char **ptr;
  2. *ptr = malloc(sizeof(ptr) + 1);
  3. ptr = malloc(sizeof(dictionaryLine) + 1);
  4.  
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:
Expand|Select|Wrap|Line Numbers
  1. char **ptr;
  2. ptr = malloc(rows * sizeof(int *));
  3. for (int x = 0; x < rows; x++)
  4. {
  5.    ptr[x] = malloc(columns * sizeof(int))
  6. }
  7.  
Jun 13 '07 #6
Savage
1,764 Expert 1GB
I don't think that's correct.
I believe it is like this:
Expand|Select|Wrap|Line Numbers
  1. char **ptr;
  2. ptr = malloc(rows * sizeof(int *));
  3. for (int x = 0; x < rows; x++)
  4. {
  5.    ptr[x] = malloc(columns * sizeof(int))
  6. }
  7.  
ilikepython is correct except that he forgot to cast them to char pointers.Rememeber:

void *malloc(size_t size);

this is malloc declararation.

So it should be:

Expand|Select|Wrap|Line Numbers
  1. char **ptr;
  2. ptr = (char**)malloc(rows * sizeof(int *));
  3. for (int x = 0; x < rows; x++)
  4. {
  5.    ptr[x] = (char*)malloc(columns * sizeof(int))
  6. }
  7.  
Savage
Jun 13 '07 #7
gucci09
20
hey thanks you guys...but how do i know how big the rows and columns are based on the dictionary file i have?
Jun 13 '07 #8
Savage
1,764 Expert 1GB
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
Jun 13 '07 #9
gucci09
20
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.
Jun 14 '07 #10
Savage
1,764 Expert 1GB
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
Jun 14 '07 #11
gucci09
20
so i am still having the same problem. here is my code. i keep getting a seg fault.


Expand|Select|Wrap|Line Numbers
  1. s=(char **)malloc(1*sizeof(char*));
  2.         s[0]=(char *)malloc(strlen(s[i]));
  3.  
  4.         i++;
  5.  
  6.  
  7.     while(!feof(finptr)){
  8.         s=(char **)realloc(s,i*sizeof(char*));
  9.         s[i]=(char *)realloc(s[i],strlen(s[i]));    
  10.     }
Jun 18 '07 #12
Savage
1,764 Expert 1GB
so i am still having the same problem. here is my code. i keep getting a seg fault.


Expand|Select|Wrap|Line Numbers
  1. s=(char **)malloc(1*sizeof(char*));
  2.         s[0]=(char *)malloc(strlen(s[i]));
  3.  
  4.         i++;
  5.  
  6.  
  7.     while(!feof(finptr)){
  8.         s=(char **)realloc(s,i*sizeof(char*));
  9.         s[i]=(char *)realloc(s[i],strlen(s[i]));    
  10.     }

Have you freed the memory?

Savage
Jun 18 '07 #13
gucci09
20
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.


Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5.  
  6. int main(int argc, char *argv[]){
  7.  
  8.     FILE *finptr;        //file pointer to input file
  9.  
  10.     int i=0;        //for incrementing
  11.     int loweraddress;    //lower address of file stored in array
  12.     int upperaddress;    //upper address of file stored in array
  13.     int counter=0;        //counts how many strings in file    
  14.     char **s;        //pointer to character sting
  15.     char hold[]="Conspiracy Theory's are cool!";
  16.  
  17.  
  18. /*-------------------------------------------------------------------------------*/
  19. //test for too few arguements    
  20.     if(argc<2){
  21.         printf("\nToo few arguements \n");
  22.         printf("Usage: <program> <input file> \n");
  23.         return 0;
  24.     }
  25.  
  26. //test for too many arguements
  27.     if(argc>2){
  28.         printf("\nToo many arguements \n");
  29.         printf("Usage: <program> <input file> \n");
  30.         return 0;
  31.     }
  32.  
  33. //test to see if input file can be opened and open it
  34.     if((finptr=fopen(argv[1],"rt"))==NULL){
  35.         printf("\n Cannot open input file \n");
  36.         return 0;
  37.  
  38.     }
  39.  
  40. //malloc array and copy in words
  41.  
  42.         if((s=(char **)malloc(1*sizeof(char*)))==NULL){
  43.             printf("malloc failed\n");
  44.         }
  45.         fgets(hold,100,finptr);
  46.         s[i]=(char *)malloc(strlen(hold));
  47.         strcpy(s[i],hold);
  48.         printf("%s \n",s[i]);
  49.  
  50.  
  51.         i++;
  52.  
  53.  
  54.     while(!feof(finptr)){
  55.         if((s=(char **)realloc(s,i*sizeof(char*)))==NULL){
  56.             printf("malloc failed \n");
  57.         }
  58.         fgets(hold,100,finptr);
  59.         s[i]=(char *)realloc(s[i],i*strlen(hold));
  60.         strcpy(s[i],hold);
  61.         printf("%s \n",s[i]);
  62.         i++;
  63.  
  64.  
  65.     }
  66.  
  67.     printf("%d - %d \n", &s[0], &s[i]);
  68. /*----------------------------------------------------------------------------------*/
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78. free(s);
  79. return 0;
  80. }
Jun 18 '07 #14
Savage
1,764 Expert 1GB
With this line here,you allocate only enough memory for 4 char *:
Expand|Select|Wrap|Line Numbers
  1. if((s=(char **)malloc(1*sizeof(char*)))==NULL){
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
Jun 18 '07 #15
gucci09
20
alright i changed my code around now bc i decided i dont need a 2 dimentional array. what am i doing wrong?


Expand|Select|Wrap|Line Numbers
  1. //calculate array size
  2.  
  3.         while(i!= EOF){
  4.             i=fgetc(finptr);
  5.             counter++;
  6.         }            
  7.  
  8. //malloc array and copy in words
  9.         s=(char *)malloc(counter);
  10.  
  11.         i=0;
  12.         while(i<counter){
  13.             fscanf(finptr,"%c",&s[i]);
  14.             printf("%c", s[i]);
  15.             i++;
  16.         }
  17. //store address of array    
  18.     loweraddress=(int)&s[0];
  19.     upperaddress=(int)&s[counter];
  20.  
  21.  
  22.  

basically the characters are not being copied in
and i dunno if the address are working right either
Jun 19 '07 #16
weaknessforcats
9,208 Expert Mod 8TB
//malloc array and copy in words
s=(char *)malloc(counter);

i=0;
while(i<counter){
fscanf(finptr,"%c",&s[i]); <<<<<<<<
printf("%c", s[i]);
i++;
}
You need to allocate memory for s[i] before you copy to it.
Jun 20 '07 #17

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: songfire | last post by:
Hi everybody! Just wondering if it is possible to point to variables in the heap. For example, is this okay? int * ptr_to_DAIA; // pointer to dynamically allocated integer array ptr_to_DAIA =...
5
by: nmtoan | last post by:
Hi, I could not find any answer to this simple question of mine. Suppose I have to write a program, the main parts of it are as follows: #include <blahblah.h> struct {
48
by: Michel Rouzic | last post by:
I know it must sound like a newbie question, but I never really had to bother with that before, and I didn't even find an answer in the c.l.c FAQ I'd like to know what's the really proper way...
11
by: skumar434 | last post by:
Hi everybody, I am faceing problem while assigning the memory dynamically to a array of structures . Suppose I have a structure typedef struct hom_id{ int32_t nod_de; int32_t hom_id;
2
by: flyvholm | last post by:
According to a couple of other threads you can't use sizeof with dynamic arrays - you'll have to keep track of the memory allocated. In my case, strings are filled into a dynamic array by a...
6
by: bwaichu | last post by:
Is my understanding of the allocation of these correct? I used fixed sized allocations for the example below, so I realize there is some optimization that can be done to those. I would like to...
4
by: wyrmmage | last post by:
hello :) I need to make a dynamically allocated array of pointers, using a .hpp and .cpp file; how do I accomplish this? I think I know how to make an array of pointers, and I know how to make a...
7
by: Serpent | last post by:
The C-FAQ describes some techniques here: http://c-faq.com/aryptr/dynmuldimary.html I was using something slightly different from the C-FAQ and I was wondering if it was legal. Say I want a...
3
by: DaveJ | last post by:
Hi, This is quite a simple question (hopefully). If I create a vector (on any container) on the heap e.g. std::vector<std::string* m_VectorOfStrings = new vector<std::string>; I know that...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.