473,758 Members | 5,909 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 #1
18 2353
Hello Svata,
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:
<snip>
Are there other solutions? What are the pros and cons using
array/pointer?
Your code is fine, especially if the item_name read should be truncated
to 10 characters (this limit could be defined as constant, BTW, to make
code change easier).

Cheers,
Loic.

Nov 13 '06 #2
svata wrote:
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.
You /must not/ return a pointer to an array which is a local
non-static variable of the function.
I read some articles, some other posts and come to this solution:

char *read_name(void ){
static char item_name[11];
(fx:snip)
return item_name; /* return string in the form of character array */
}
So you /must not/ do this. The variable `item_name` evaporates when
the function returns, so the pointer to it isn't pointing anywhere
and any use of it gets you undefined behaviour -- which is a Very
Bad Thing.

You must return a pointer to store which will outlive the function
call: for example:

* a static array, usually a bad idea because different uses of the
function will share that array.

* mallocated store (which the using code will have to free)

* store passed in as an argument (so it's the caller's problem)

* mix as desired (carefully)

--
Chris "hantwig efferko VOOM!" Dollin
Meaning precedes definition.

Nov 13 '06 #3
lo******@gmx.ne t wrote:
Hello Svata,
>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:

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

Your code is fine,
Not so, as my reply to svata explains.

--
Chris "hantwig efferko VOOM!" Dollin
"People are part of the design. It's dangerous to forget that." /Star Cops/

Nov 13 '06 #4
Chris Dollin, the complete idiot, wrote:
svata wrote:
>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.

You /must not/ return a pointer to an array which is a local
non-static variable of the function.
>I read some articles, some other posts and come to this solution:

char *read_name(void ){
static char item_name[11];

(fx:snip)
> return item_name; /* return string in the form of character array */
}

So you /must not/ do this.
OK, OK, I'm blind. I read it three times and didn't see `static`.
As soon as I posted, I saw it.

Sorry sorry sorry. Egg egg egg. Time to go hone.
You must return a pointer to store which will outlive the function
call: for example:

* a static array, usually a bad idea because different uses of the
function will share that array.
So you were OK to do what you did, except there's a gotcha you
need to beware of.

--
Chris "hantwig efferko VOOM!" Dollin
"Life is full of mysteries. Consider this one of them." Sinclair, /Babylon 5/

Nov 13 '06 #5
"svata" <sv******@centr um.czwrote in message
news:11******** **************@ h54g2000cwb.goo glegroups.com.. .
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:
....
Are there other solutions? What are the pros and cons using
array/pointer?
Returning a pointer to a static buffer is a common technique. However,
that has the problem that your callers need to be aware of that, and
they'll likely need to strdup() the results if they want to call the
function frequently. It also means the function is not reentrant, which
can kill you if you try to call that function from multiple threads,
signal handlers, etc.

malloc()ing a new buffer for each call is also done at times. That
solves the above problems, but it means that the caller needs to know to
free() the strings you return when they're done with them, or they'll
end up with a memory leak.

The last common option is to require the caller to provide a buffer (and
its size!) for you; you just put the string into their buffer. By
requiring the caller to do the malloc(), it makes it easier for them to
see they need to do a free(). Or they might use a local array, if they
know how big to make it.

The question in all cases is what to do if the buffer isn't big enough
for the input. If you _know_ that a certain size will never be
exceeded, you can go with that, but such "knowledge" usually turns out
to be incorrect after several maintenance/release cycles. You'll need
to spend as much time figuring out this problem as you are deciding who
allocates the buffer where.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking

--
Posted via a free Usenet account from http://www.teranews.com

Nov 13 '06 #6
svata wrote:
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?
Stephen below suggests the caller supplying the buffer
(and length). It is sometimes desirable for the caller
to repeatedly call the function each time receiving as
much of the data as can fit in the buffer.

e.g.

int foo (char *buf, int length)
{
/* copy data_to_be_retu rned into buf, not exceeding length */
return 0;
}
....
char buf[20];
int length = foo (buf, sizeof buf);
while (length) {
length = foo (buf, sizeof buf);
/* Use the data here */
}

You can also make the called function behave differently
depending on the argument supplied, supplying a NULL pointer
for the buffer would return the length needed (hard to do with
the above example). This has the disadvantage of seriously
confusing the reader, so comment clearly in header, etc.

e.g.

int foo (char *buf)
{
/* process and store data to be returned in a static buffer */
if (!buf) {
return length_of_data_ to_be_returned;
} else {
memcpy (buf, data_to_be_retu rned, length_of_data_ to_be_returned) ;
}
return 0;
}
....
int length = foo (NULL);
char *buf = malloc (length);
if (!buf) {
/* error!!! */
} else {
foo (buf);
}
....
free (buf);
Basically, every solution will have pros and cons, and
it's up to you to choose which is best for the situation.
There is no "one-good-way" that can be applied to all
situations; be thankful that you've got such a variety
of methods available :-)

goose,
hth

Nov 13 '06 #7


svata wrote On 11/13/06 09:44,:
[...]
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.
[...]
Others have addressed your immediate question. I'd like
to draw your attention to two other issues:

printf("Enter the description: ");
if (fgets(item_nam e, sizeof(item_nam e), stdin) != NULL){
Question 12.4 in the comp.lang.c Frequently Asked Questions
list http://www.c-faq.com/ explains why you'd be well-advised to
insert fflush(stdout); between these two lines.
/* 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 */
;
}
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?

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

Nov 13 '06 #8
svata wrote:
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 prefer making the caller pass in a buffer and a buffer size, and
then the function fills in the buffer and returns the length filled in.
(Or returns a status code and passes the length back via a
pointer parameter, etc.)

This way, the function is not tied to any particular memory
management scheme, and can be called from various places in
your code without having to waste any memory or perform any
acrobatics.

It is also common to allow the function to accept NULL as the
buffer, in which case it will return the size of buffer required, and
then the caller can allocate space if necessary and call the
function again.

Nov 13 '06 #9
"svata" <sv******@centr um.czwrites:
[...]
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
[...]
Are there other solutions? What are the pros and cons using
array/pointer?
See the comp.lang.c FAQ, <http://www.c-faq.com/>, particularly
questions 7.5a and 7.5b.

--
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 14 '06 #10

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

Similar topics

1
3329
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
2332
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
6019
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
2565
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
5087
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
1960
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
4879
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
1988
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
9489
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
9298
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
10072
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
9906
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
9885
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
9737
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8737
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6562
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
5172
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

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.