473,769 Members | 6,739 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A function returning string or pointer

Hello to all,

as a result from my previous post I'm busy with splitting code into
functions.
The one problem ( out of many ) I encounter is how to properly
use/code a function which returns either array of characters(stri ng) or
a pointer to this array.

I read some articles, some other posts and come to this solution:
char *read_name(void ){
static char item_name[11];
char *p_item_name;

printf("Enter the description: ");
if (fgets(item_nam e, sizeof(item_nam e), stdin) != NULL){
/* if the input contains a new line */
if (( p_item_name = strchr(item_nam e, '\n')) != NULL ){
*p_item_name = '\0'; /* get rid of new line */
}
else {
while(getchar() != '\n'){ /* get rid of the rest in the buffer */
;
}
}
}
return item_name; /* return string in the form of character array */
}

Are there other solutions? What are the pros and cons using
array/pointer?

svata

Nov 13 '06
18 2357
Eric Sosman wrote:
A good effort, but it overlooks one possibility: What does
getchar() return at end-of-input (or I/O error)? What will
this code do if that happens?
It is EOF, am I right?

svata

Nov 14 '06 #11


svata wrote On 11/14/06 05:44,:
Eric Sosman wrote:

> A good effort, but it overlooks one possibility: What does
getchar() return at end-of-input (or I/O error)? What will
this code do if that happens?


It is EOF, am I right?
Yes, that's what getchar() will return. Now, what
will your code do if that happens?

--
Er*********@sun .com

Nov 14 '06 #12
Eric Sosman wrote:
Yes, that's what getchar() will return. Now, what
will your code do if that happens?
So, it should look as follows:

while(getchar() != EOF && getchar() != '\n'){
;
}

One has to check for EOF as well, I suppose.

svata

Nov 14 '06 #13
svata wrote:
Eric Sosman wrote:
> Yes, that's what getchar() will return. Now, what
will your code do if that happens?

So, it should look as follows:

while(getchar() != EOF && getchar() != '\n'){
;
}

One has to check for EOF as well, I suppose.
You realise that code will test two different characters?
(Even if they have the same value ...)

--
Chris "hantwig efferko VOOM!" Dollin
Nit-picking is best done among friends.

Nov 14 '06 #14
svata wrote:
Eric Sosman wrote:
Yes, that's what getchar() will return. Now, what
will your code do if that happens?

So, it should look as follows:

while(getchar() != EOF && getchar() != '\n'){
;
}

One has to check for EOF as well, I suppose.
Don't call getchar() twice. Each call will return a different value.
Also you're discarding both return values. I think you may find the
following code snippet more suited to what you were probably trying to
do.

int c;
....

while((c = getchar()) != EOF) {
if(c != '\n') {
DO_SOMETHING;
}
}

Now a return value of EOF could be caused either by end of file or some
kind of I/O error. Presumably, you'd consider the former to be a normal
condition and the latter as an error of some severity. To find which of
them caused getchar() to return EOF, you might use ferror() and/or
feof(). The former returns non-zero if the stream has encountered an
I/O error, while the latter returns true when end of file has been
reached on the stream. Once you determine that then appropriate action
can be taken. Use clearerr() to reset the stream's end of file and
error indicators.

Nov 14 '06 #15
svata wrote:
Eric Sosman wrote:
> Yes, that's what getchar() will return. Now, what
will your code do if that happens?

So, it should look as follows:

while(getchar() != EOF && getchar() != '\n'){
}

One has to check for EOF as well, I suppose.
This is agonizing. To put it out of its misery:

int flushln(FILE *f) {
int ch;

while ((EOF != (ch = getc(f)) && (ch != '\n')) continue;
return ch;
}

Replace your code with "someint = flushln(stdin); " and decide what
needs doing when (and if) someint becomes EOF.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

Nov 14 '06 #16
CBFalconer wrote:
This is agonizing. To put it out of its misery:

int flushln(FILE *f) {
int ch;

while ((EOF != (ch = getc(f)) && (ch != '\n')) continue;
return ch;
}
This is correct code, but tricky code. It's a sufficiently common idiom
in C programs that I would expect any programmer to be able to
understand it, along with the even commoner idiom:
while((ch = getc(fp)) != EOF) { ... }

That said, however, in my opinion it is best practise to avoid trying to
put the whole loop contents into the loop condition when it's not needed.

If one wants to write simple, easy to read C, I think one should adhere
to the rule that loop bodies are supposed to make changes to program
state, while (while, for, if) conditions are supposed to make a decision
based on the current program state but not make changes to that state.

Here's another way to write it, which is simpler to read in my opinion:

int flushln(FILE *fp)
{
int ch;

do
{
ch = getc(fp);
}
while(ch != EOF && ch != '\n');

return ch;
}

--
Simon.
Nov 14 '06 #17
Simon Biber wrote:
CBFalconer wrote:
This is agonizing. To put it out of its misery:

int flushln(FILE *f) {
int ch;

while ((EOF != (ch = getc(f)) && (ch != '\n')) continue;
return ch;
}

This is correct code, but tricky code. It's a sufficiently common idiom
in C programs that I would expect any programmer to be able to
understand it, along with the even commoner idiom:
while((ch = getc(fp)) != EOF) { ... }

That said, however, in my opinion it is best practise to avoid trying to
put the whole loop contents into the loop condition when it's not needed.

If one wants to write simple, easy to read C, I think one should adhere
to the rule that loop bodies are supposed to make changes to program
state, while (while, for, if) conditions are supposed to make a decision
based on the current program state but not make changes to that state.

Here's another way to write it, which is simpler to read in my opinion:

int flushln(FILE *fp)
{
int ch;

do
{
ch = getc(fp);
}
while(ch != EOF && ch != '\n');

return ch;
}
This may be okay for flushing input but if you want to process it, then
having the test for EOF and NL at the bottom is wasteful as the code
within the DO clause has to do the test anyway.

Nov 14 '06 #18
In article <11************ *********@m7g20 00cwm.googlegro ups.com>,
santosh <sa*********@gm ail.comwrote:
> do
{
ch = getc(fp);
}
while(ch != EOF && ch != '\n');
>This may be okay for flushing input but if you want to process it, then
having the test for EOF and NL at the bottom is wasteful as the code
within the DO clause has to do the test anyway.
A reasonable compiler will optimise that if you could. Even if it
doesn't, clarity is usually much more important than that kind of
micro-optimisation.

-- RIchard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Nov 14 '06 #19

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

Similar topics

1
3330
by: john | last post by:
Relatively new to C coding, so any help would greatly be appreciated. I'm having problems try to return my string array from my parsing function. When I do a printf I am getting the correct value for my first element but my subsequent printf's will return garbage. Can someone let me know what I am doing wrong. Thanks in advance. -jlewis
14
2333
by: Stegano | last post by:
I am learning C Programming after working with Java for 5 years. I want to know where can I find the source files for C language itself. For example strcat is a function, which concatenates two strings. I want to read how this function is implemented in its native form, where can I find its corresponding .c file. I am using gcc version 3.3.1 (Thread model POSIX) on cygwin with Eclipse IDE. A grep on a function name lists many .h and .c...
2
6022
by: None | last post by:
Hello, 1. The prototype of function signal in signal.h: void (*signal(int sig, void (*func)(int)))(int); is some complex to me. Would you please explain it to me in detail with the C language syntax itself. Thank you!
14
2566
by: Mike Labosh | last post by:
How do you define whether the return value of a function is ByRef or ByVal? I have a utility class that cleans imported records by doing *really heavy* string manipulation in lots of different methods, and it operates on DataTables in excess of 100,000 rows of anywhere between 4 and 30 columns. I'd like to get the functions to return ByRef for greater speed and memory efficiency, but I can't see how to do that. --
8
2685
by: ais523 | last post by:
I use this function that I wrote for inputting strings. It's meant to return a pointer to mallocated memory holding one input string, or 0 on error. (Personally, I prefer to use 0 to NULL when returning null pointers.) It looks pretty watertight to me, but my version of lint complains about use of deallocated pointers, etc. Is this code completely safe on all input, or have I missed something? /* Header files included in the program...
9
5088
by: cmk128 | last post by:
Hi Why put * in front of the function name in the declaration? int (*write)(struct inode *, struct file *, const char *, int); thanks from Peter (cmk128@hotmail.com)
11
1961
by: Antoninus Twink | last post by:
What's the correct syntax to define a function that returns a pointer to a function? Specifically, I'd like a function that takes an int, and returns a pointer to a function that takes an int and returns a string. I tried this: gchar *(*f(gint n))(gint) { /* logic here */ }
5
2641
by: Travis | last post by:
I am using a function that returns a const char * that is usually a word, etc. How can I check to see if what it returns is empty? I tried if (function() == "") and (function() == NULL) and (function() == '/0'). But then I see that the those if statements are flagging true when the function returns back a char * or no length
26
4882
by: aruna.mysore | last post by:
Hi all, I have a specific problem passing a function pointer array as a parameter to a function. I am trying to use a function which takes a function pointer array as an argument. I am too sure about the syntax of calling the same. #include <stdio.h> void fp1()
13
1989
by: Sri Harsha Dandibhotla | last post by:
Hello all. I recently came across a function declaration as : char(*(*x()))(); This was not in some code but it was in a C questions thread on some group. I tried to decipher what it returns but couldn't make complete sense out of it. Can someone please explain what this function is supposed to return and expand it step by step. Thanks,
0
9589
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
9423
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
10049
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
9997
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6675
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
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3965
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3565
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
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.