473,378 Members | 1,482 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

C Neophyte needs guidance to String/Char processing

Environment: OS X (v10.4.10) running gnu gcc 4.0.1 compiler.

Greetings...
I'm toying with functions passing strings written in pure ANCI C. I've written a simple 'C' program below to develop an understanding how C works.

Questions:
1) What will be in variable 'q'?
2) Is there another way to write: char* myFunction() {}?

Regards,
Ric.

BTW: the GNU compiler gives me a warning that 'myFunction()' returns the address of a local variable.
------------------------------------------------------------------------------------------------------
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. char *myFunction();
  5.  
  6. int main() { 
  7.    char * b, q, *r;
  8.    b=myFunction();
  9.    q=*b;  // <--- what will 'q' contain?   
  10.    printf("\nDone.\n");
  11.    return 0;
  12. } // end main() 
  13.  
  14. // ----------------------------------------------------
  15.  
  16. char* myFunction() { 
  17.    char str[15]; 
  18.    strcpy(str, "Hello, Ric!\n");
  19.    printf("Inside myFunction: %s",str);
  20.    return (char *) str;
  21. }  
  22.  
  23.  
================================================== ======

Here's the output (via Mac OS X using gcc 4.0.1 compiler):
Expand|Select|Wrap|Line Numbers
  1. [/Users/Ric/workarea/C workspace/c_strings]./myTest
  2. Inside myFunction: Hello, Ric!
  3.  
  4. Done.
  5.  
  6.  
Aug 30 '07 #1
4 1838
gsi
51
Hi ,
The program's result is undefined. A local pointer is returned(Arrays are implicitly passed and returned as pointers in c). Hence on scope exit, the pointer is no longer a valid address in memory. In line 9, q may still have 'H' in it, if no other activation record has been pushed on to the stack.

One way of doing this is to create an array (Either heap or stack) from main, pass that to the function , do a strcpy on the passed arrayand return the same.

like,
Expand|Select|Wrap|Line Numbers
  1.  
  2. int main(void){
  3. //your initialization's
  4. char str[15];//Dynamic memory allocation can also be done.
  5. b=myFunction(str);
  6. // your code
  7. }
  8. char* myFunction(char *str) { 
  9.    strcpy(str, "Hello, Ric!\n");
  10.    printf("Inside myFunction: %s",str);
  11.    return (str);
  12. }
  13.  
Thanks,
gsi.
Aug 30 '07 #2
hi, i'm a neophyte in this community. i already searched most of the web sites to find codes on hashing in c language but still i failed, all i found were codes in java programming.. anyways, can you provide me examples and explanations on the following?:
>hashing methods:
*division methods
*middle square method
*multiplication method
*fibonacci hashing

thanks in advance...
jay-em

and p.s. can you send it directly to my e-mail address <Email removed by MODERATOR, according to posting guidelines>
Aug 30 '07 #3
Hi ,
The program's result is undefined. A local pointer is returned(Arrays are implicitly passed and returned as pointers in c). Hence on scope exit, the pointer is no longer a valid address in memory. In line 9, q may still have 'H' in it, if no other activation record has been pushed on to the stack.

One way of doing this is to create an array (Either heap or stack) from main, pass that to the function , do a strcpy on the passed arrayand return the same.

like,
Expand|Select|Wrap|Line Numbers
  1.  
  2. int main(void){
  3. //your initialization's
  4. char str[15];//Dynamic memory allocation can also be done.
  5. b=myFunction(str);
  6. // your code
  7. }
  8. char* myFunction(char *str) { 
  9.    strcpy(str, "Hello, Ric!\n");
  10.    printf("Inside myFunction: %s",str);
  11.    return (str);
  12. }
  13.  
Thanks,
gsi.
Thanks for your speedy reply.
I read your message and began working on what you told me, via Apple's XCode (GNU gcc compiler). I've expanded the code to the following:

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. char *myFunction(); 
  5. char *anotherfunction(char *b);
  6.  
  7. int main (int argc, const char * argv[]) {
  8.     char * b, q, *r; 
  9.     b=myFunction();
  10.     q = *b;    
  11.      r= anotherfunction(b);    
  12.     // .....     
  13.     return 0;
  14. }
  15.  
  16. // --------------------------------------------------------------------------------------
  17.  
  18. char *myFunction() {
  19.     char str[8];
  20.         strcpy(str, "Hello");
  21.     return (char *) str;
  22. }   
  23.  
  24. // --------------------------------------------------------------------------------------
  25.  
  26. char *anotherfunction(char *b)  {
  27.     printf("Inside anotherfunction: %s",b);
  28.    return (char *) b;    
  29. } // end anotherfunction().
  30.  
  31.  
The following is what I got via the dubugger:
Expand|Select|Wrap|Line Numbers
  1. Program loaded.
  2. sharedlibrary apply-load-rules all
  3. run
  4. [Switching to process 648 local thread 0xf03]
  5. Running…
  6. Pending breakpoint 1 - ""main.c:25" resolved
  7. (gdb) print b
  8. $1 = 0xbffff5d8 "\030\366\377\277X\035"
  9. (gdb) print q
  10. $2 = 72 'H'
  11. (gdb) print r
  12. $3 = 0xbffff5d8 "\030\366\377\277X\035"
  13. (gdb) cont
  14. Inside anotherfunction: Hello
  15. Debugger stopped.
  16. Program exited with status value:0.Continuing.
  17.  
So the value of 'b' as returned by myFunction() is some hex address.
The value of 'q' is the first char of the array 'str' (i.e., str[0]).

------

Even though the compiler gives a warning that I'm passing the address of a local variable, it DOES pass that value.

But since we get that warning, I'm assuming that this value won't always be available. So, under what conditions might this not be so?

Regards,

Ric.
Aug 30 '07 #4
JosAH
11,448 Expert 8TB
But since we get that warning, I'm assuming that this value won't always be available. So, under what conditions might this not be so?
The C Standard has a nice definition about that: it defines 'undefined behaviour'.
What you just did in your program causes undefined behaviour and anything can
happen then. You're just lucky that you got reasonable output when you ran
your program; but maybe tomorrow it won't behave reasonable anymore. Nobody
knows and don't rely on its behaviour totday: it is undefined.

Either malloc() memory in that function and fill it with a ('\0' terminated) string or
pass a buffer to that function which is used by that function to put a string in.
Returning the address of a local variable is a real nono and you should never
rely on it.

kind regards,

Jos
Aug 30 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: stanlo | last post by:
hi to everyone, this is still a follow up of my project ,mathematical expression.this project is meant to evaluate mathemtical expressions with oparators,+,-,*,/.more than two operands can be done,...
1
by: rusttree | last post by:
I'm working on a program that manipulates bmp files. I know the offset location of each piece of relevent data within the bmp file. For example, I know the 18th through 21st byte is an integer...
13
by: M | last post by:
Hi, I've searched through the previous posts and there seems to be a few examples of search and replacing all occurrances of a string with another string. I would have thought that the code...
19
by: Paul | last post by:
hi, there, for example, char *mystr="##this is##a examp#le"; I want to replace all the "##" in mystr with "****". How can I do this? I checked all the string functions in C, but did not...
0
by: ma740988 | last post by:
I inquired about utilizing a vector of pairs just yesterday and after receiving some feedback, I got to thinking my thoughts with regards to my initial 'approach' was flawed to begin with: ...
9
by: James | last post by:
Complete neophyte to VC++. I do have a base knowledge of how API calls work and the general structure of these applications, but I'm getting bogged down with details. Just a few, relatively...
4
by: pigeonrandle | last post by:
Quickie time! Is indexing using String to get individual characters 'as quick' as converting the String to a Char and then using Char? Is the conversion to Char worth the processing? In...
1
by: lumo2000 | last post by:
hello NG, i am trying to do some syscalls and therefore i need to put some text together. its no problem as long i want to cout the text to display, but when i want to use it as parameter for...
0
by: UncleRic | last post by:
Environment: Mac OS X (10.4.10) on MacBook Pro I'm a Perl Neophyte. I've downloaded the XML::Parser module and am attempting to install it in my working directory (referenced via PERL5LIB env): ...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.