473,908 Members | 3,934 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

return a string

Hello,

How to I do to return a string as a result of a function.
I wrote the following function:

char prt_tralha(int num)
{
int i;
char tralha[num];

tralha = "#";
for( i = 0; i < num-1; i++ )
strcpy(tralha, strcat(tralha," #"));

return tralha;
}

And I really like to use it, thus:

int main()
{
printf("%s \n", prt_tralha(5));

return 0;
}

But when I compile it, gcc shows this message:

tmp.c: In function `prt_tralha':
tmp.c:16: error: incompatible types in assignment
tmp.c:20: warning: return makes integer from pointer without a cast
tmp.c:20: warning: function returns address of local variable

Thanks,

Nascimento
Nov 14 '05 #1
23 3624
Nascimento wrote:
Hello,

How to I do to return a string as a result of a function.
I wrote the following function:

char prt_tralha(int num)
{
int i;
char tralha[num];

tralha = "#";
for( i = 0; i < num-1; i++ )
strcpy(tralha, strcat(tralha," #"));

return tralha;
}

And I really like to use it, thus:

int main()
{
printf("%s \n", prt_tralha(5));

return 0;
}

But when I compile it, gcc shows this message:

tmp.c: In function `prt_tralha':
tmp.c:16: error: incompatible types in assignment
tmp.c:20: warning: return makes integer from pointer without a cast
tmp.c:20: warning: function returns address of local variable

Thanks,

Nascimento


#include <stdio.h>
#include <stdlib.h>
const char * string_function (void)
{
static const char * my_text = "My text";
return my_text;
}

int main(void)
{
printf("%s\n", string_function ());
return EXIT_SUCCESS;
}

Fundamentally, you pass a pointer to a string; not
the string.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library
Nov 14 '05 #2

Nascimento wrote:
Hello,

How to I do to return a string as a result of a function.
I wrote the following function:

There are two ways to "return" a string from a function. One is to
simply return it...
char prt_tralha(int num)
I.E. char * ptr_tralha(int num)

Here we return a pointer to char, or string. The problem with this is
the return value can't be an automatic variable, so you'll need to work
with malloc.

Another method is to make the string part of the argument list. This is
probably prefered, since the memory management takes place outside of
the function and is (arguably) easier.

I.E. char ptr_tralha(int num, char *ret)
{
int i;
char tralha[num];
Assuming the later method, tralha would simply be the argument to this
function, and not declared here.

tralha = "#";
for( i = 0; i < num-1; i++ )
strcpy(tralha, strcat(tralha," #"));

return tralha;
There would be no need to "return" tralha here, since it was passed in
via pointer in the argument list.
}

And I really like to use it, thus:

int main()
{
printf("%s \n", prt_tralha(5));
try this instead:

char tralha[5];
ptr_tralha(5,tr alha);
printf("%s \n", tralha);

return 0;
}

But when I compile it, gcc shows this message:

tmp.c: In function `prt_tralha':
tmp.c:16: error: incompatible types in assignment
Well, of course. The function is (was) returning a char, but you were
trying to use it as if it were a char *.
tmp.c:20: warning: return makes integer from pointer without a cast
tmp.c:20: warning: function returns address of local variable

Thanks,
Hope this helps. I'm sure others will have suggestions as well.

-Jason
Nascimento


Nov 14 '05 #3
Nascimento,
you cannot assign a char to a string like that:
tralha = "#"
you can do it like this: tralha[0]='#';
A more elegant code for your purpose goes like this:

--- tralha.c ---

void
ptr_tralha(char *s)
{
while (*s != '\0') /* while the contents of s are different
* from NULL */
*s++ = '#'; /* s = '#' . increment s */
}
int
main(void)
{
char s[5];
ptr_tralha(s);
puts(s);

return 0;
}

Nov 14 '05 #4

Nascimento wrote:
int i;
char tralha[num];

tralha = "#";
for( i = 0; i < num-1; i++ )
strcpy(tralha, strcat(tralha," #"));


Oh, no! Look what's happening here! You are trying to copy chars into
the tralha[] array without using the proper notation. This is bad.

What you want to do is use array substript notation or pointer
arithmetic. Substript is by far easier for the beginner.

tralha[0] = '#'; /* Use single quotes for char */
for( i = 1; i < num-1; i++ ) /* i=1, not 0 (see above) */
tralha[i] = '#'; /* again, copy a char only */
tralha[i] = '\0'; /* don't forget the terminator! */

You don't need (or want) strcpy or strcat when you are building an
array from scratch.

Nov 14 '05 #5
un************@ gmail.com (Nascimento) writes:
How to I do to return a string as a result of a function.
I wrote the following function:

char prt_tralha(int num)
{
int i;
char tralha[num];

tralha = "#";
for( i = 0; i < num-1; i++ )
strcpy(tralha, strcat(tralha," #"));

return tralha;
}

And I really like to use it, thus:

int main()
{
printf("%s \n", prt_tralha(5));

return 0;
}

But when I compile it, gcc shows this message:

tmp.c: In function `prt_tralha':
tmp.c:16: error: incompatible types in assignment
tmp.c:20: warning: return makes integer from pointer without a cast
tmp.c:20: warning: function returns address of local variable
All three error messages are correct.

tralha = "#";
error: incompatible types in assignment

You can't assign strings like that. The name of a string variable (or
of any array) is implicitly converted, in most contexts, to a pointer
to its first element. See section 6 of the C FAQ,
<http://www.eskimo.com/~scs/C-faq/top.html>. You can initialize a
char array with a string literal, but I don't think that's what you
want in this case.

return tralha;
warning: return makes integer from pointer without a cast
warning: function returns address of local variable

You declared your function to return a char (a single character
value). You're trying to return a char*. The types are incompatible.
(The "integer" in the first warning refers to type char, which is an
integer type.)

Even if prt_tralha() were declared to return a char*, returning the
address of a local variable would be invalid. Your array tralha
ceases to exist as soon as the function terminates. Your main program
would receive a pointer to a non-existent object, and any attempt to
use it will invoke undefined behavior. In the worst case, it will
work as expected, failing only at the most inconvenient possible
moment. (The compiler isn't required to diagnose this error, but gcc
is kind enough to do so anyway.)

Other problems:

Your declaration "char tralha[num];" declares a variable length array
(VLA). This is a new feature in C99. If you're not concerned about
portability to compilers that don't support VLAs, that's fine, but you
should be aware that such support is not (yet?) universal. You might
consider using malloc() to allocate the memory dynamically.
for( i = 0; i < num-1; i++ )
strcpy(tralha, strcat(tralha," #"));


What is the purpose of the strcpy()? strcat() appends "#" to your
string (assuming tralha is a valid string in the first place) and
returns a pointer to its first element. The strcpy() copies the
nstring onto itself. That's either undefined behavior or a no-op, I
don't remember which.

What you're trying to do is set tralha to a string of num '#'
characters. Using strcat() for this is wasteful.

for (i = 0; i < num; i ++) {
tralha[i] = '#';
}
tralha[num] = '\0';

or

memset(tralha, '#', num);
tralha[num] = '\0';

And since you need space for the trailing '\0', the size of tralha had
better be at least num+1.

Since C doesn't treat arrays as first-class objects (you can't assign
them, compare them, or pass them as parameters, at least not
directly), dealing with character strings can be tricky, especially
when you don't know until execution time how big they're going to be.

If you want a function to return a variable-sized string (or any
array) to its caller, there are basically 3 ways to do it.

1. Let the caller allocate the array. The caller then needs to pass
in the address of the array and its size (and you need to decide what
to do if the caller's array isn't big enough). See the standard
fgets() function for an example.

2. Return a pointer to a static variable. Since static variables
continue to exist after the function returns, this avoids the problem
you had. The drawback is that there's only one allocated result; if
you call your function multiple times, each call will clobber the
previous result. This is especially bad in the presence of recursion
<OT>or multi-threading</OT>.

3. Allocate the result array in the function using malloc(). This is
probably the most flexible method, but it then require the caller to
free() the array when it's finished with it.

--
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 '05 #6


Nascimento wrote:
Hello,

How to I do to return a string as a result of a function.
I wrote the following function:

char prt_tralha(int num)
{
int i;
char tralha[num];

tralha = "#";
for( i = 0; i < num-1; i++ )
strcpy(tralha, strcat(tralha," #"));

return tralha;
}

And I really like to use it, thus:

int main()
{
printf("%s \n", prt_tralha(5));

return 0;
}

But when I compile it, gcc shows this message:

tmp.c: In function `prt_tralha':
tmp.c:16: error: incompatible types in assignment
tmp.c:20: warning: return makes integer from pointer without a cast
tmp.c:20: warning: function returns address of local variable


You seem to be confused about several points. The
comp.lang.c Frequently Asked Questions (FAQ) list

http://www.eskimo.com/~scs/C-faq/top.html

covers some of them: Section 6 will help you understand
gcc's first complaint, Question 8.1 explains the second,
and Question 7.5 covers the third.

However, gcc did not catch all your errors. One that
it didn't catch is the strcpy() call: you are passing it
two strings that overlap, but strcpy() requires the source
and destination areas to be distinct. When you try to use
strcpy() on overlapping strings, anything at all might
happen. (Since the overlap is "perfect" -- the source and
destination are exactly the same string -- the strcpy()
call is pointless anyhow. I think this goes back to your
misunderstandin gs about strings; see FAQ section 8.)

Read the FAQ, re-read your textbook, and start over.
Good luck!

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

Nov 14 '05 #7
On 29 Apr 2005 14:04:10 -0700, un************@ gmail.com (Nascimento)
wrote:
Hello,

How to I do to return a string as a result of a function.
I wrote the following function:

char prt_tralha(int num)
Here, you're saying to return a character, not a string. You want
char * prt_tralha(int num)
where the returned value will be a pointer to a character array
(string).
{
int i;
char tralha[num];
You can't declare a variable size array. What you can do is
char *tralha;
tralha = malloc(num);
but remember to check the return value to make sure the malloc
succeeded. One possibility is
if (tralha == NULL)
return NULL;
Also, since you are allocating new memory, it needs to be freed at
some point. More below on this.
tralha = "#";
You can't just assign strings. (Your first compiler error below.) You
can do
strcpy(tralha, "#");
for( i = 0; i < num-1; i++ )
strcpy(tralha, strcat(tralha," #"));
This makes little sense, but I think I can guess what you're trying to
do. Make a string with num '#'s, right? How about
for( i = 0; i < num-1; i++ )
strcat(tralha, "#");
return tralha;
This is OK now, since you've allocated new memory for tralha. In your
original, you returned the address of a local array, which will be
invalid as soon as you return from the function. This is why you got
the third compiler error. The second error was because you were
returning a pointer, when you told the compiler you wanted to return a
char.}

And I really like to use it, thus:

int main()
{
printf("%s \n", prt_tralha(5));
Now, we have the problem that prt_tralha has allocated memory which
needs to be freed. In your test program it doesn't matter, but in a
real program, every call to prt_tralha would allocate more memory, and
you could eventually run out. That's what we call a memory leak. One
way to fix this is

char *temp = prt_tralha(5);
if (temp != NULL)
{
printf("%s \n", temp);
free temp;
}
return 0;
}

But when I compile it, gcc shows this message:
Some hints: Look up the definitions and try to find example uses of
every library function you use, such as strcpy, strcat, malloc, free
above. I referred to all your compiler diagnostics as "errors" on
purpose. Unless you know exactly why the compiler issued a warning,
and you know for certain that it's harmless, consider it an error and
fix it. There is hardly ever a good reason for ignoring compiler
warnings.

Get a good tutorial. I recommend "The C Programming Language" by
Kernighan and Ritchie, which is a good tutorial and reference.
tmp.c: In function `prt_tralha':
tmp.c:16: error: incompatible types in assignment
tmp.c:20: warning: return makes integer from pointer without a cast
tmp.c:20: warning: function returns address of local variable

Thanks,

Nascimento


--
Al Balmer
Balmer Consulting
re************* ***********@att .net
Nov 14 '05 #8
mu********@yaho o.com-dot-br.no-spam.invalid (iru_muzgo) writes:
Nascimento,
you cannot assign a char to a string like that:
tralha = "#"
you can do it like this: tralha[0]='#';
A more elegant code for your purpose goes like this:

--- tralha.c ---

void
ptr_tralha(char *s)
{
while (*s != '\0') /* while the contents of s are different
* from NULL */
No. NULL is (a macro that expands to) a null *pointer* constant.
'\0' is a null character, sometimes referred to as NUL. Using the
term NULL to refer to a character value is misleading.
*s++ = '#'; /* s = '#' . increment s */
}
int
main(void)
{
char s[5];
ptr_tralha(s);
puts(s);

return 0;
}


Your array s is not initialized before you pass its address to
ptr_tralha(). Inside ptr_tralha(), you loop over the array until you
find a '\0' character, but there's no reason to assume that you ever
will. Unless there happens to be a '\0' character somewhere within s,
the loop in ptr_tralha() will go past the end of the array, invoking
undefined behavior.

I just tried compiling and running your program, and it printed a
string of 5 '#' characters followed by a newline. Apparently there
just happened to be no '\0' characters in s itself, but there just
happened to be a '\0' character immediately following it in memory.
This is just one of the infinitely many possible consequences of
undefined behavior.

--
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 '05 #9
Alan Balmer <al******@att.n et> writes:
On 29 Apr 2005 14:04:10 -0700, un************@ gmail.com (Nascimento)
wrote:

[...]
{
int i;
char tralha[num];


You can't declare a variable size array.


Yes you can, if you have a C99 compiler or a pre-C99 compiler that
supports the feature. (The form of the diagnostics implies that he's
probably using gcc, which does support VLAs.)

I covered the portability issues in my previous followup.

--
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 '05 #10

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

Similar topics

3
4534
by: Phil Powell | last post by:
My first time working with a PHP class, and after 6 hours of working out the kinks I am unable to return a value from the class, so now I appeal to the general audience what on earth did I do wrong this time? This is the code the retrieves the values: if (($hasRegistered || $hasPreRegistered) && !empty($uplinenumber)) { // CHECK TO SEE IF UPLINE NUMBER IS A VALID NUMBER $regNumberGenerator = new RegNumberGenerator($uplinenumber,...
12
4141
by: Jose Fernandez | last post by:
Hello. I'm building a web service and I get this error. NEWS.News.CoverNews(string)': not all code paths return a value This is the WebMethod public SqlDataReader CoverNews(string Sport) {
12
3814
by: Michael Maes | last post by:
Hello, I have a BaseClass and many Classes which all inherit (directly) from the BaseClass. One of the functions in the BaseClass is to (de)serialize the (inherited) Class to/from disk. 1. The Deserialization goes like: #Region " Load "
7
1812
by: nafri | last post by:
hello all, I want to create a function that returns the first element of the Array that is input to it. However, the Input Array can be an Array of points, double, or anyother type, which means the return type of the function depends on the type of the objects the Input array holds. I can have the return type as Object, but it has problems like late binding and more importantly the client has to always Cast it. For example. class...
16
4937
by: Dany | last post by:
Our web service was working fine until we installed .net Framework 1.1 service pack 1. Uninstalling SP1 is not an option because our largest customer says service packs marked as "critical" by Microsoft must be installed on their servers. Now german Umlaute (ä, ü, ö) and quotes are returned incorrectly in SOAP fault responses. This can be easily verified: Implement the following in a web service method (just raises a SOAPException with a...
9
3227
by: MSDNAndi | last post by:
Hi, I have a set of simple webservices calls that worked fine using .NET Framework 1.0. I am calling a Java/Apache based webservices, the calling side is not able to supply a proper WSDL. What it does is to call a webservice with two parameters, one being a integer, the other one being a "String" which contains XML (not the best practice, however that is the target interface and we cannot change that).
18
4078
by: Pedro Pinto | last post by:
Hi there once more........ Instead of showing all the code my problem is simple. I've tried to create this function: char temp(char *string){ alterString(string); return string;
2
2484
by: utab | last post by:
Dear all, I tried sth easy(actually this was an exercise) but I tried to use the standard lib. heavily for this problem(as far as I can). There was one point I could not figure out. The problem is : ../a.out 1.3+3.2+.1+40/3*8/7-4*5-32 The program will parse the argument and find the result of the above expression. I have two versions(the 2nd is working , not perfect ;-}),
6
2419
KoreyAusTex
by: KoreyAusTex | last post by:
If anyone can help me figure out the what the missing return statements are, I think it might be the fact that I need to add a return false in the getValue()? import java.util.*; public class Card { // instance variables //suits private int suit; private int spades;
14
2050
by: =?Utf-8?B?QmVu?= | last post by:
Hi all, I'm trying to understand the concept of returning functions from the enclosing functions. This idea is new to me and I don't understand when and why I would need to use it. Can someone please shed some light on this subject? Thanks a lot, Ben
0
10035
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
11339
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
10915
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...
0
10537
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...
1
8096
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
7248
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
5933
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...
1
4772
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
4336
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.