Re: dynamic array of ints
From: Robert Strandh (strandh_at_labri.fr)
Date: 07/28/04
- Next message: Ian Woods: "Re: Theory of programming"
- Previous message: Ian Shef: "Re: generating a mouse event by a java program"
- In reply to: John Hanley: "dynamic array of ints"
- Next in thread: rossum: "Re: dynamic array of ints"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 28 Jul 2004 21:29:17 +0200
"John Hanley" <jdhanley@telusplanet.net> writes:
> I have an interesting problem and I'm not sure the best way to do this.
>
> I am reading in a variable number of integers from a file (eg. 001 002 003
> 004 012 015). At compile time I have no idea how many will be there. But I
> need to parse them out and put them in an array.
>
> I could do an fscanf and just read until '\n', however I won't know how many
> are there and thus don't know how large to make my array.
>
> I could read it in as one large string, traverse through and count the
> number of ints and then allocate memory based on that. However I am not
> sure what to use to read the ints from the string. sscanf works but
> multiple calls to it start at the beginning of the string each time. And
> it seems like a sloppy way to do things anyway.
>
> Are there any suggestions as to what approach to take with this? I wanted
> to avoid using a link list as it seems like alot of work for maybe less than
> 10 ints I need to parse out.
>
> Suggestions? Ideas?
You could do it recursively. Code not tested:
int *
read_ints(FILE *stream, int n, int *how_many)
{
if(end_of_line(stream))
{
*how_many = n;
return malloc(n * sizeof(int));
}
else
{
int number = read_int(stream);
int *result = read_ints(stream, n + 1, how_many);
result[n] = number;
return result;
}
}
...
int
main(void)
{
FILE *stream = ...;
int how_many;
int *numbers = read_ints(stream, 0, &how_many);
...
}
-- Robert Strandh --------------------------------------------------------------------- Greenspun's Tenth Rule of Programming: any sufficiently complicated C or Fortran program contains an ad hoc informally-specified bug-ridden slow implementation of half of Common Lisp. ---------------------------------------------------------------------
- Next message: Ian Woods: "Re: Theory of programming"
- Previous message: Ian Shef: "Re: generating a mouse event by a java program"
- In reply to: John Hanley: "dynamic array of ints"
- Next in thread: rossum: "Re: dynamic array of ints"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|