Re: pointers to char
- From: gordy <gordy@xxxxxxxxxxx>
- Date: Sat, 15 Oct 2005 23:11:48 +0100
On Sat, 15 Oct 2005 15:16:09 -0400, Kenneth Brody wrote:
> gordy wrote:
>>
>> Newbie question, please by gentle.
>>
>> I'm trying to read in a text file containing the days of the week, one on
>> each line. Each line should be pointed to by an array of pointers to char
>> but I'm ending up with each pointer pointing to the same string.
>>
>> #include <stdio.h>
>> #include <stdlib.h>
>>
>> #define DAYS 7
>>
>> int main()
>> {
>> int count = 0, bytes_read;
>> char *strings[DAYS], *buffer = NULL;
>> FILE *fp;
>> size_t size = 1;
>>
>> if((fp = fopen("days", "r")) == NULL)
>> {
>> puts("File not found");
>> exit(EXIT_FAILURE);
>> }
>>
>> while(bytes_read = (getline(&buffer ,&size, fp)) != -1)
>
> I don't know what getline() does. While my system has a getline()
> function, it is totally different that yours, as mine is prototyped
> as:
>
> char *getline(char *prompt);
>
> I am guessing, based on context, that you pass it:
>
> The address of a char* for the buffer. If the pointer is
> NULL, then a buffer will be allocated for you.
>
> The address of an int, to return the size of the buffer.
>
> The FILE* stream to read from.
>
> And it returns the number of bytes read.
>
> Continuing with my assumptions, if buffer is not NULL, then it
> will use the buffer/length which is passed to it.
>
>> strings[count++] = buffer;
>
> If my assumptions above are true, then once the buffer is allocated
> for the first call, it will continue using the same buffer, as your
> "char *buffer" is no longer NULL.
following this advice I changed the code to:
while(bytes_read = (getline(&buffer ,&size, fp)) != -1)
{
strings[count++] = buffer;
buffer = NULL;
}
>
>>
>> while(count--)
>> printf("\t\t%s", *(strings + count));
and:
printf("\t\t%s", strings[count]);
>
> Is ther any reason you don't use "strings[count]" here? It's much
> clearer, at least for me.
>
>>
>> fclose(fp);
>> return 0;
>> }
>>
>> file days:
>> Monday
>> Tuesday
>> Wednesday
>> Thursday
>> Friday
>> Saturday
>> Sunday
>>
>> I'm sure I'm missing something silly here, any help would be appreciated.
>
> If any of my assumptions above are wrong, then you are going to have to
> describe how your getline() function works.
Your assumptions were spot on, it's now working as I wanted it to.
many thanks for your help.
.
- References:
- pointers to char
- From: gordy
- Re: pointers to char
- From: Kenneth Brody
- pointers to char
- Prev by Date: Re: Use of static ?
- Next by Date: Re: Binary Tree
- Previous by thread: Re: pointers to char
- Next by thread: Re: pointers to char
- Index(es):
Relevant Pages
|