473,804 Members | 3,250 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

strings and functions


I am used to Delphi and VB, where functions can return strings. I
recently starting learning C and my findings are that you can have
external functions build strings, but the function cannot return the
string itself, rather, it needs to update a variable that is an array or
points to an array. Correct?

Below is a 'simple' test to work with a string that was created in an
external function (and external file). Based on the result I get (_@),
I know I don't fully "get it" yet. Any help would be appreciated.

//MAIN.C

#include<stdio. h>

main()

{

char *data_from_func tion;

my_function(dat a_from_function );

printf("Data results from My Function: %s\n");

}

//MYFUNCTION.C

my_function(cha r *strData)

{

strData = "HELLO WORLD\n";

}

(Linux 9 i386)

#gcc main.c myfunction.c

#./a.out

Data results from My Function: _@
--
Posted via http://dbforums.com
Nov 13 '05 #1
12 2713
c_monty wrote:
I am used to Delphi and VB, where functions can return strings. I
recently starting learning C and my findings are that you can have
external functions build strings, but the function cannot return the
string itself, rather, it needs to update a variable that is an array or
points to an array. Correct?

Below is a 'simple' test to work with a string that was created in an
external function (and external file). Based on the result I get (_@),
I know I don't fully "get it" yet. Any help would be appreciated.

//MAIN.C

#include<stdio. h>
main()
The main() function should have a return type:
int main(void)

{
char *data_from_func tion;
my_function(dat a_from_function );
printf("Data results from My Function: %s\n");
Perhaps this should have been:
printf("Data results from my_function: %s\n",
data_from_funct ion); /* you forgot this */ } //MYFUNCTION.C
my_function(cha r *strData)
{
strData = "HELLO WORLD\n";
}
Pointers are passed by value in C.
If you want to change a pointer, pass the address
or a pointer to the pointer:
void my_function(cha r * * strData)
{
*strData = "Hellow World\n";
}

or copy the data to the location of the original
array:
void my_other_functi on(char * strData)
{
strcpy(strdata, "Hello again.\n");
return;
}

int main(void)
{
char string_one[640];
char * string_two;

my_function(&st ring_two);
my_other_functi on(string_one);
printf("Results :\n%s\n%s\n",
string_one, string_two);
return 0;
}

(Linux 9 i386)
#gcc main.c myfunction.c
#./a.out

Data results from My Function: _@
--
Posted via http://dbforums.com

--
Thomas Matthews
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html

Nov 13 '05 #2
c_monty <me*********@db forums.com> writes:
I am used to Delphi and VB, where functions can return strings. I
recently starting learning C and my findings are that you can have
external functions build strings, but the function cannot return the
string itself, rather, it needs to update a variable that is an array or
points to an array. Correct?
Correct.
Below is a 'simple' test to work with a string that was created in an
external function (and external file). Based on the result I get (_@),
I know I don't fully "get it" yet. Any help would be appreciated.

//MAIN.C

#include<stdio. h>

main()
int main (void)
{
char *data_from_func tion;

my_function(dat a_from_function );

printf("Data results from My Function: %s\n");
Do you mean `printf("Data results from My Function: %s\n", data_from_funct ion);'?
}
Insert `return 0;' before the closing brace.

//MYFUNCTION.C

my_function(cha r *strData)
{
strData = "HELLO WORLD\n";
}
`strData' is local to `my_function'. You make `strData' point to a string
literal. Then the function execution ends, and the value of `strData' is
forgotten.

You can return a string literal (more precisely: a pointer to the first
character of string literal) from a function like this:
#include <stdio.h>

const char *my_function (void)
{
return "HELLO WORLD";
}

int main (void)
{
printf ("Data results from My Function: %s\n", my_function ());
return 0;
}
A string literal cannot be modified. If you need to modify the string, you
must copy it to an array:
#include <stdio.h>
#include <string.h>

void my_function (char *const buffer)
{
strcpy (buffer, "HELLO WORLD");
}

int main (void)
{
/* Must be large enough for the string,
including the terminating '\0' character. */
char my_buffer [12];

my_function (my_buffer);

my_buffer [1] = 'A';

printf ("Data results from My Function: %s\n", my_buffer);
return 0;
}

(Linux 9 i386)
<OT>
No such thing. Linux is currently at version 2.4.21; the development branch
is at version 2.6.0-test3.
</OT>
#gcc main.c myfunction.c


Please invoke gcc with at least the following flags: -O -Wall -ansi -pedantic

I recommend `-W' in addition to that.

Martin
Nov 13 '05 #3
c_monty wrote:

I am used to Delphi and VB, where functions can return strings. I
recently starting learning C and my findings are that you can have
external functions build strings, but the function cannot return the
string itself, rather, it needs to update a variable that is an array or
points to an array. Correct?
Pretty much. "C functions can't return strings" is just
a special case of "C functions can't return arrays," because
a string in C is just an array of `char' elements formatted
in a particular way. Recommended reading: Section 6 "Arrays
and Pointers" in the comp.lang.c Frequently Asked Questions
(FAQ) list

http://www.eskimo.com/~scs/C-faq/top.html
Below is a 'simple' test to work with a string that was created in an
external function (and external file). Based on the result I get (_@),
I know I don't fully "get it" yet. Any help would be appreciated.

//MAIN.C

#include<stdio. h>

main()

{

char *data_from_func tion;

my_function(dat a_from_function );

printf("Data results from My Function: %s\n");
There are minor solecisms elsewhere, but this is the first
Real Live Error: You've used the "%s" specifier to tell printf()
to output a string, but you haven't told printf() what string
you want it to output! printf() trusts you, looks in the place
where the string's `char*' pointer would have been if you'd
supplied one, gets some kind of garbage, and then there's no
guarantee of what might happen. You've landed yourself in the
perilous land called Undefined Behavior.

}

//MYFUNCTION.C

my_function(cha r *strData)

{

strData = "HELLO WORLD\n";
Here's the second Real Live Error: You don't understand
that C arguments are passed by value, not by reference.
See Question 4.8 in the FAQ.
}

(Linux 9 i386)

#gcc main.c myfunction.c
Since you're still somewhat shaky in C, it would be a
good idea to crank up gcc's warning levels a bit. I use

gcc -Wall -W -ansi -pedantic -O2 ...

.... except that I omit "-ansi -pedantic" for programs that
can't tolerate such rigidity, and I raise the optimization
level higher than "-O2" when circumstances warrant it.
#./a.out

Data results from My Function: _@


Could have been anything at all, or nothing at all.
Undefined Behavior is, well, undefinable. Folks around
here are fond of saying U.B. might make demons fly out
of your nose. Years ago on this same newsgroup, people
had a wider variety of imaginative U.B. examples, but the
nasal demons seem to have crowded out the creativity.

--
Er*********@sun .com
Nov 13 '05 #4
Thomas Matthews <Th************ **********@sbcg lobal.net> broke the eternal silence and spoke thus:
void my_function(cha r * * strData)
{
*strData = "Hellow World\n";
}
This is bad (right?) since strData now points to a constant string that will
vanish when my_function returns...
void my_other_functi on(char * strData)
{
strcpy(strdata, "Hello again.\n");
return;
}


Also bad, since you don't know in general how much space strData has
associated with it, if any.

If I've done foot-in-mouth again here, I apologize ;)

--
Christopher Benson-Manica | Jumonji giri, for honour.
ataru(at)cybers pace.org |
Nov 13 '05 #5


On 8/22/2003 1:31 PM, pete wrote:
c_monty wrote:
<snip>
char *my_function(ch ar *strData)
{
strData = malloc(sizeof "HELLO WORLD\n");
if (strData) {
strcpy(strData, "HELLO WORLD\n");
}
return strData;
}

Why would you have "my_functio n" take an argument in this case? Wouldn't you
really write this as:

char *my_function()
{
char *strData;
strData = malloc(sizeof "HELLO WORLD\n");
if (strData) {
strcpy(strData, "HELLO WORLD\n");
}
return strData;
}

so that instead of being called as:
data_from_funct ion = my_function(dat a_from_function );


it can be called as:

data_from_funct ion = my_function();

Regards,

Ed.
Nov 13 '05 #6
On Fri, 22 Aug 2003 13:48:54 -0400, c_monty wrote:

I am used to Delphi and VB, where functions can return strings. I
recently starting learning C and my findings are that you can have
external functions build strings, but the function cannot return the
string itself, rather, it needs to update a variable that is an array or
points to an array. Correct?
These other environments are likely returning pointers (Java calls them
references) as well. C permits pointer arthmetic which gives C it's
razor's edge. Be careful.
my_function(dat a_from_function );

printf("Data results from My Function: %s\n");


You just forgot to add the string you want to print:

printf("Data results from My Function: %s\n", data_from_funct ion);

In C the way to "return strings" is to return a pointer to an array
of characters:

char *
tostr(void)
{
return "hello";
}

Mike
Nov 13 '05 #7
Ed Morton wrote:

On 8/22/2003 1:31 PM, pete wrote:
c_monty wrote:
<snip>
char *my_function(ch ar *strData)
{
strData = malloc(sizeof "HELLO WORLD\n");
if (strData) {
strcpy(strData, "HELLO WORLD\n");
}
return strData;
}


Why would you have "my_functio n" take an argument in this case?


It's a vestigial feature from the original post.
Wouldn't you really write this as:

char *my_function()
{
char *strData;
strData = malloc(sizeof "HELLO WORLD\n");
if (strData) {
strcpy(strData, "HELLO WORLD\n");
}
return strData;
}

so that instead of being called as:
data_from_funct ion = my_function(dat a_from_function );


it can be called as:

data_from_funct ion = my_function();


Yes, I think that's better.

--
pete
Nov 13 '05 #8
at***@nospam.cy berspace.org wrote:

Thomas Matthews <Th************ **********@sbcg lobal.net>
broke the eternal silence and spoke thus:
void my_function(cha r * * strData)
{
*strData = "Hellow World\n";
}
This is bad (right?) since strData now points to a
constant string that will vanish when my_function returns...


No. Those kinds of strings persist.
The strData pointer itself, will disappear,
but the desired side effect will happen.
The external pointer that *strData points to,
will be pointed at the string.
void my_other_functi on(char * strData)
{
strcpy(strdata, "Hello again.\n");
return;
}


Also bad, since you don't know in general how much space strData has
associated with it, if any.


That particular criticism is valid.

This works:

#include <stdio.h>

void my_function(cha r * * strData)
{
*strData = "Hellow World\n";
}

int main(void)
{
char *data_from_func tion;

my_function(&da ta_from_functio n);
printf("Data results from My Function: %s\n",
data_from_funct ion);
return 0;
}

--
pete
Nov 13 '05 #9
pete <pf*****@mindsp ring.com> spoke thus:
> void my_function(cha r * * strData)
> {
> *strData = "Hellow World\n";
> }
This is bad (right?) since strData now points to a
constant string that will vanish when my_function returns...

No. Those kinds of strings persist.
The strData pointer itself, will disappear,
but the desired side effect will happen.
The external pointer that *strData points to,
will be pointed at the string.


So, since it's a string literal, it still ends up in the static section of
memory or something? The function still doesn't work if strData happens to be
NULL... And even if it does work, you can't do something like
*strData[3]='a', right, since the string is literal?

--
Christopher Benson-Manica | Jumonji giri, for honour.
ataru(at)cybers pace.org |
Nov 13 '05 #10

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

Similar topics

4
12288
by: Trying_Harder | last post by:
Firstly, are functions defined in strings.h (`strcasecmp' and `strncasecmp') ANSI? if yes , then why am I getting an implicit declaration warning only with -Wall (Warnings all) flag? and if not, why am I not getting warnings with `gcc -ansi -pedantic blah.c' Secondly , is there a function in `C' for comparing strings ignoring their cases? Only criterion is this has to be ANSI compliant (being
4
10738
by: John Devereux | last post by:
Hi, I would like some advice on whether I should be using plain "chars" for strings. I have instead been using "unsigned char" in my code (for embedded systems). In general the strings contain ASCII characters in the 0-127 range, although I had thought that I might want to use the 128-255 range for special symbols or foreign character codes. This all worked OK for a long time, but a recent update to the compiler on my system has...
7
5644
by: arkobose | last post by:
hey everyone! i have this little problem. consider the following declaration: char *array = {"wilson", "string of any size", "etc", "input"}; this is a common data structure used to store strings of any lengths into an array of pointers to char type variable. my problem is: given the declaration
3
1271
by: darrel | last post by:
Often, I want to use a string in multiple functions on a page. I can declare and re-set the string in each function, or I can just delcare the string outside of the individual functions so that they can all see it. This works fine. My question is if there is any reason NOT to go ahead and declare ALL strings at the top? Is there a performance/memory hit in doing that? Or is it simply a matter of clean code syntax/layout?
4
455
by: CoreyWhite | last post by:
/* WORKING WITH STRINGS IN C++ IS THE BEST WAY TO LEARN THE LANGUAGE AND TRANSITION FROM C. C++ HAS MANY NEW FEATURES THAT WORK TOGETHER AND WHEN YOU SEE THEM DOING THE IMPOSSIBLE AND MAKING COMPACT COHERENT CODE THAT WORKS WITH STRINGS, IT ALL BEGINS TO MAKE SINCE*/ /* The basics of C++ are Classes, that build Types. Which are used to create quick and dirty routines in the smallest possible space. The Classes & Routines uses the...
28
6068
by: hlubenow | last post by:
Hello, I really like Perl and Python for their flexible lists like @a (Perl) and a (Python), where you can easily store lots of strings or even a whole text-file. Now I'm not a C-professional, just a hobby-programmer trying to teach it myself. I found C rather difficult without those lists (and corresponding string-functions). Slowly getting into C-strings, I thought, what if I take a C-string and
95
5442
by: hstagni | last post by:
Where can I find a library to created text-based windows applications? Im looking for a library that can make windows and buttons inside console.. Many old apps were make like this, i guess ____________________________________ | | | ------------------ | | | BUTTON | | | ...
16
1881
by: InDepth | last post by:
Now that .NET is at it's fourth release (3.5 is coming soon), my very humble question to the gurus is: "What have we won with the decision to have string objects immutable? Or did we won?" Ok. It's a broad, and maybe a very silly question to ask, but still. I mean, what good has it brought to us? What advantages immutable strings have against mutable ones?
0
9588
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
10589
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
9161
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
6857
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
5527
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...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4302
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
3828
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2999
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.