| | |
char** for string array problem
Please support our C advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Dec 2007
Posts: 10
Reputation:
Solved Threads: 0
Hi, I use char* for string handling because I read strings from a file and I don't know the length of these strings. The problem comes when I need to keep some strings in an array. I think char** is the best thing for that goal. But again since I don't know how many strings I will hold, I'm stuck in allocating memory for new strings to be hold. For example;
matches is the function checks the string for my intention. The line that malloc is included is a bit silly, I know
. I need to access the strings in future. I think I could explain my problem. I want to allocate a new char* space and bind my str to it. But how?
Thanks...
C Syntax (Toggle Plain Text)
char* str; char** match_list; while (fscanf(inp, "%s", str) != EOF) { if (matches(str)) { *match_list = (char**)malloc(sizeof(char*)); *(match_list + i) = str; i++; } }
matches is the function checks the string for my intention. The line that malloc is included is a bit silly, I know
. I need to access the strings in future. I think I could explain my problem. I want to allocate a new char* space and bind my str to it. But how?Thanks...
Let's start by clearing up an obvious misunderstanding about pointers.
>char *str;
>fscanf(inp, "%s", str);
This is broken. An uninitialized pointer does not mean a pointer to unlimited space. It means you're not allowed to dereference that pointer or compare it to anything until you initialize it.
You still need to guesstimate a size for reading strings from input, even if that size is a chunk and you append the chunks using dynamic memory. Get that right and then you can worry about an array of strings, because the solution is very similar.
>char *str;
>fscanf(inp, "%s", str);
This is broken. An uninitialized pointer does not mean a pointer to unlimited space. It means you're not allowed to dereference that pointer or compare it to anything until you initialize it.
You still need to guesstimate a size for reading strings from input, even if that size is a chunk and you append the chunks using dynamic memory. Get that right and then you can worry about an array of strings, because the solution is very similar.
New members chased away this month: 4
Well I really couldn't get what you meant but I will answer to the point I think you asked...k
Well you can allocate two dimensional array as follows:
In this way you can dynamically allocate the number of strings and also their lengths by just altering he str_nos and str_len .I hope this helps
Well you can allocate two dimensional array as follows:
c Syntax (Toggle Plain Text)
char **array; //Your two dimensional array int str_nos=10; //No of strings you want to have int str_len=60; //Maximum length of each string array=malloc( str_nos * sizeof(char *) ); //Above st allocates memory for no of char pointers or strings for(i=0;i<str_nos;i++) { a[i]=malloc( str_len * sizeof(char *) ); }
In this way you can dynamically allocate the number of strings and also their lengths by just altering he str_nos and str_len .I hope this helps
Last edited by csurfer; Apr 1st, 2009 at 1:00 pm.
I Surf in "C"....
Just a tip: since you are reallocating new memory when you run out of space, you probably want to use realloc. This will keep all the data you had copied into your array previously.
Last edited by death_oclock; Apr 1st, 2009 at 2:22 pm.
instead of using malloc() (or realloc) poorly.... might i suggest sticking with the tried and true:
because i'm fairly certain you're not doing an embedded application that is limited for RAM.
but mangling malloc() like you're doing will certainly find the limits of your computer memory after you fill it full of leaks.
C Syntax (Toggle Plain Text)
char stringblock[MAX_NUM_LINES][MAX_LINE_LEN];
but mangling malloc() like you're doing will certainly find the limits of your computer memory after you fill it full of leaks.
•
•
Join Date: Dec 2007
Posts: 10
Reputation:
Solved Threads: 0
@Narue:
thanks for reply. although you said it is broken I initialize the str every time I read a word from the file. After initialziation I work with str and matches function work properly.
@csurfer:
Thanks for reply but in your way I think i have to read file twice to have a correct size of match list. Isn't that a problem for performance when reading big files?
@jephthah:
Thanks for reply. I don't know what will be the values of MAX_NUM_LINES and MAX_LINE_LEN values before I read the file and changing these values is not possible after run time I think.
@death_oclock:
Is that possible I allocate one char* space beforehand and reallaocate space one by one after I found new words that matches my specifications? Using that way make sense but I have a char* named str and I want to keep that pointer in an array named match_list. As I wrote on the code it is char** type. I don't know how to tie these values. Thanks
•
•
•
•
>char *str;
>fscanf(inp, "%s", str);
This is broken. An uninitialized pointer does not mean a pointer to unlimited space. It means you're not allowed to dereference that pointer or compare it to anything until you initialize it.
@csurfer:
•
•
•
•
In this way you can dynamically allocate the number of strings and also their lengths by just altering he str_nos and str_len .I hope this helps
@jephthah:
•
•
•
•
char stringblock[MAX_NUM_LINES][MAX_LINE_LEN];
@death_oclock:
•
•
•
•
Just a tip: since you are reallocating new memory when you run out of space, you probably want to use realloc. This will keep all the data you had copied into your array previously.
>although you said it is broken I initialize the str every time I read a word from the file.
Hmm, I can interpret this one of two ways:
Arbitrary length input takes more work, and often the basic input functions are weak without a bit of scaffolding around them to get what you want. For example, here's a delimited string input function that can be used to read words:
Take careful note of how I handled the memory, this is a common pattern that you can reuse for an array of pointers to char. You can use this example to neatly fix your broken code and find the answer to the original problem of creating a dynamic array. You're welcome.
Hmm, I can interpret this one of two ways:
- You're saying the code you posted isn't equivalent to the code you're actually using.
- You're saying that I'm wrong and the code you posted isn't broken.
Arbitrary length input takes more work, and often the basic input functions are weak without a bit of scaffolding around them to get what you want. For example, here's a delimited string input function that can be used to read words:
c Syntax (Toggle Plain Text)
#include <stdio.h> #include <stdlib.h> #include <string.h> #define GROW_BY 32 /* Arbitrary size */ char *reads ( FILE *in, char *delim ) { char *result = NULL; size_t size = 0; size_t capacity = 0; int ch; while ( ( ch = getc ( in ) ) != EOF ) { if ( size == capacity ) { char *temp; capacity += GROW_BY; temp = realloc ( result, capacity + 1 ); if ( temp == NULL ) { /* This is a weak solution because it results in loss of data. Recommend better error handling */ free ( result ); result = NULL; break; } result = temp; } /* Order is important here; run *after* the resize step */ if ( strchr ( delim, ch ) != NULL ) break; result[size++] = ch; } if ( result != NULL ) result[size] = '\0'; return result; } int main ( void ) { char *s; while ( ( s = reads ( stdin, " \n" ) ) != NULL ) { printf ( ">%s<\n", s ); free ( s ); } return 0; }
New members chased away this month: 4
•
•
Join Date: Dec 2007
Posts: 10
Reputation:
Solved Threads: 0
In fact it is 2nd case.
Also if you have a big experience then you should know it is not a big deal that people can correct you. If you are uncomfortable with that using forums is not suitable for you. I'm not saying I am an expert but you are wrong about what you've written in previous post. Technically speaking, I initialize and reinitiaize str pointer with every word I read from file. It is not a char pointer array it is just a char pointer. After that I make comparison or whatever I need. At least I know that is possible and I suggest you to accept your fault. I don't want to be offending but if you want I could send you the code. Because it is one of my friend's project I prefer not to publish it here.
•
•
•
•
because I'm very rarely wrong when it comes to the standard language/library, and when I am it's not the people asking beginner questions who are able to correct me successfully.
![]() |
Similar Threads
- Char/String problems (C++)
- 2d array problem (Java)
- Linked List of Array (C++)
- string array problem (C)
- Copy a string to a 2d array of type char (C++)
- from string to array + lowercase (C++)
- Array problem in Pascal (Pascal and Delphi)
- Is there a simplest way to work this array problem? (C++)
- Comparing String with a 2D Array (C++)
Other Threads in the C Forum
- Previous Thread: help needed
- Next Thread: kmeans program.
Views: 1571 | Replies: 18
| Thread Tools | Search this Thread |
Tag cloud for C
#include * append array arrays asterisks binarysearch calculate changingto char character cm command copyimagefile creafecopyofanytypeoffileinc database directory dynamic execv feet fgets file floatingpointvalidation fork forloop framework function functions getlogicaldrivestrin givemetehcodez grade graphics gtkwinlinux hacking histogram homework ide include incrementoperators input intmain() iso kernel keyboard kilometer lazy license linked linkedlist linux list lists looping loopinsideloop. lowest matrix microsoft mqqueue number oddnumber odf opensource openwebfoundation overwrite owf pause pdf performance pointer posix probleminc process program programming radix recursion recv recvblocked research reversing scripting segmentationfault sequential single socket socketprogramming spoonfeeding standard string student systemcall testing threads turboc unix urboc user variable whythiscodecausesegmentationfault windowsapi






