Solved

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

Posted on 2003-11-04
4
278 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

911 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

15 Experts available now in Live!

Get 1:1 Help Now