Solved

Passing string as a reference to a function.........

Posted on 2003-11-04
4
266 Views
Last Modified: 2010-05-18
Hi,
    How to pass a character array to a function using call-by-reference? I have a function which performs the operation as same as atof (converting string to float). When i passed the string as a reference, i got the following  error.

" error C2664: 'myatod' : cannot convert parameter 1 from 'char [9]' to 'char &'"

My program is given below.

#include<iostream>
using namespace std;
float myatod(char&);
main() {
      char str[]="-345.678";
      float k;
      k = myatod(str);
      cout<<"\n K: "<<k;
      return 1;
}


float myatod(char &s) {
   // Content of the sub routine
         ..........................
         ..........................
         ..........................
           
}

   Let me know where is the mistake.
Thanx.
0
Comment
Question by:hemanexp
  • 2
4 Comments
 
LVL 10

Expert Comment

by:Sys_Prog
ID: 9677023
You function as shown above recieves a reference to a single character and not a character array, while u are actually passing a character array to it.

Arrays are always passed by reference [meaning of reference as per C].
i.e. Here Even if u say

float myatod ( char *s )

Then, only the base address [address of 0th location] of the passed array gets passed. Thus I don't think u need to pass it by C++ reference.

HTH

Amit
0
 
LVL 10

Expert Comment

by:Sys_Prog
ID: 9677037
You can pass a reference to a pointer but that isn't needed in your case

You can do that using

float myatod ( char * &s )

Now  A refernce to a char * [i.e. a char pointer] is being passed.

This is useful if u need to modify the contents of the pointer variable itself. In your case, it won't be useful/applicable
0
 
LVL 9

Expert Comment

by:_ys_
ID: 9677671
Side note, not directly related to the question.

String literals are officially typed as const char*, and should be treated as such.
const char str[]="-345.678"; // better form

Thus the function declaration becomes:
float myatod(const char*);

Which kinda reads better, as atof doesn't modify the string parameter passed - I would expect your function myatod not to modify it either.
0
 
LVL 17

Accepted Solution

by:
rstaveley earned 25 total points
ID: 9677847
The yuckiness of the required declaration should set off alarm bells in your head and make you think, "should I be doing this?"

The only reason to pass the address of a pointer to a function is if you want to change the address pointed to by the pointer (i.e. make the pointer point elsewhere). If you pass the pointer by value you can still mess around with the data pointed to by the pointer.

You've probably got the idea of passing by reference because of vague ideas of passing std::string to functions. std::string is an object and may be passed by reference for optimum performance because it is big and because you probably don't want to play around with a copy of the object. A reference (which to all intents and purposes is a pointer) to the actual object means that less data is copied into automatic variables, when a function is called.

A copy of a pointer is more efficient to work with than a reference to a pointer, assuming you don't need to adjust what the address pointed to by the pointer. The pointer is already a "reference" (in the loose sense of the word) to an object, so ask yourself if you *really* want to pass a reference to the pointer. You certainly wouldn't expect to see references to references.

My guess is that you really want to prototype the function as...

   float myatod (const  char *s);

The only reason to use...

   float myatod( char* &s);

...is if (say) you want the adjust the pointer so that it points to the white space following your floating point number in your char buffer so you can keep on parsing it, and if that's your rationale, you might be interested in the standard library istringstream class:
--------8<--------
#include <iostream>
#include <sstream>
#include <string>

int main()
{
        std::string line("100 123.456 Hello 99");
        std::istringstream isstr(line.c_str());

        int i;
        float f;
        std::string s;
        int j;

        isstr >> i >> f >> s >> j;

        std::cout
                << "i = " << i
                << ", f = " << f
                << ", s = \"" << s << '\"'
                << " and j = " << j
                << '\n';
}
--------8<--------
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now