473,960 Members | 31,901 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pointers to char

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_FAILU RE);
}

while(bytes_rea d = (getline(&buffe r ,&size, fp)) != -1)
strings[count++] = buffer;

while(count--)
printf("\t\t%s" , *(strings + count));

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.

gordy.
Nov 15 '05 #1
3 1343
gordy <go***@cwazy.co .uk> writes:
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_FAILU RE);
}

while(bytes_rea d = (getline(&buffe r ,&size, fp)) != -1)
getline() is a non-standard function.
strings[count++] = buffer;
This is a pointer assignment. You pass its address to getline(), but
unless getline() changes the value you're assigning the same pointer
value to each element of strings.

You probably want to copy the string using strcpy() -- which means
you also need to allocate memory using malloc() (and don't forget
to check whether malloc() succeeded).
while(count--)
printf("\t\t%s" , *(strings + count));
The expression *(strings + count) is better written as strings[count].
fclose(fp);
return 0;
}


--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #2
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_FAILU RE);
}

while(bytes_rea d = (getline(&buffe r ,&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.

while(count--)
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.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Nov 15 '05 #3
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_FAILU RE);
}

while(bytes_rea d = (getline(&buffe r ,&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_rea d = (getline(&buffe r ,&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.
Nov 15 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

388
22202
by: maniac | last post by:
Hey guys, I'm new here, just a simple question. I'm learning to Program in C, and I was recommended a book called, "Mastering C Pointers", just asking if any of you have read it, and if it's worth the $25USD. I'm just looking for a book on Pointers, because from what I've read it's one of the toughest topics to understand. thanks in advanced.
19
14548
by: gaga | last post by:
I can't seem to get this to work: #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *names; char **np;
1
1630
by: ketema | last post by:
Hello, I was wondering if someone could help me with a function I am trying to write. The purpose of the function is to read in text from a file in the following format: FIRSTNAME LASTNAME SCORE SCORE SCORE SCORE example: Karen Smith 100 100 100 100 John Oliver 78 90 65 51
11
429
by: Seven Kast USA | last post by:
hi What is use of pointerrs in c programming.is fasster than other types by KAST
36
2888
by: raphfrk | last post by:
I have the following code: char buf; printf("%lp\n", buf); printf("%lp\n", &buf); printf("%lp\n", buf); printf("%lp\n", buf); printf("%d\n", buf-buf);
38
2640
by: James Brown | last post by:
All, I have a quick question regarding the size of pointer-types: I believe that the sizeof(char *) may not necessarily be the same as sizeof(int *) ? But how about multiple levels of pointers to the same type? Would sizeof(char **) be the same as sizeof(char *)? And if it is, would the internal representation be the same in both cases? background on this: I'm writing a simple IDL compiler that produces 'C'
13
1940
by: arnuld | last post by:
at the very beginning of the chapter, i see some statements i am unable to understand. i know the "Pointer" takes the address of a variable, useful if, in case, we want to manipulate that variable as each Function gets its private copy of arguments: char c; char** ppc; // what is the use of "pointer to pointer" int* a; // why it is necessary to have "an array if pointers"
8
2926
by: Piotrek | last post by:
Hi, Like almost all of beginners I have problem understanding pointers. Please, look at this piece of code, and please explain me why myswap function doesn't work as it's supposed to do, whereas myswap2 is doing exactly what I want it to do - swaping pointers. Where I made a mistake? Thanks void myswap(char *pa, char *pb){ char *tmp; tmp=pa;
33
1997
by: pateldm15 | last post by:
How do I sort an string array using pointers
14
1727
by: stevenruiz | last post by:
Hello All My question mainly is how to use/reference Double Pointers? I am currently trying to understand what the meaning of a 'vector of pointers' means also? What I am trying to do is take a char array and break it up into words omitting the spaces. What needs to be noted is that I am trying to accomplish this only using char ** and char *. Therefore, I am creating it from scratch. Below is code that I have written so far:
0
10266
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10088
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11717
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
11330
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8378
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7535
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6454
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4647
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3667
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.