Solved

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

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
C Language combined operators 28 115
Dynamically allocate memory 9 64
HTTPSendRequest with WinINet delays on first call 11 42
Indy 10 not Receiving UDP broadcast 3 22
Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
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 video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

830 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