13 Replies - 914 Views - Last Post: 21 January 2013 - 03:38 AM Rate Topic: -----

#1 synlight  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 582
  • Joined: 14-September 11

Returning a char array from function

Posted 18 January 2013 - 09:57 AM

Hi!

I'm writing a program for my C++ class, and I'm trying to figure out how to return a character array as a string from a function.

I've been trying for a few hours now to figure this out. I know I cannot return an array, so I am trying to assign it to a string, and return the string. It is placing random junk in my string. (i.e. -e0)

I have to use gets and printf for I/O in this course, as per my instructor.

Here is my code:

string getName()
{
	char buffer[50];
	string name;

	printf("What is the name of this hauler?");

	gets(buffer);
	name = buffer;
	
	printf("%s", name);

	return name;

}


Please excuse the printf in the middle of the function, I am using it for testing (when I print print the buffer instead, it contains the correct hauler name).

This is beyond the scope of my program, so my professor said he doesn't have time to help me with it, which is understandable. I just REALLY want to figure this out, it seems like it shouldn't be so difficult. From what I have been reading in my research, it can be done, but I'm missing something. If i have to, I will iterate through the array and concat each letter onto the string separately, but there has to be a better way, right?

This post has been edited by synlight: 18 January 2013 - 09:57 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Returning a char array from function

#2 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5901
  • View blog
  • Posts: 12,806
  • Joined: 16-October 07

Re: Returning a char array from function

Posted 18 January 2013 - 10:14 AM

What exactly is buffer doing for you? Get rid of that, just use string. Do not use printf or gets ( never use gets, anyway ). Use cin and cout.

Use C++ entirely. If you mix C and C++ methodologies, you'll excel at neither.
Was This Post Helpful? 2
  • +
  • -

#3 jimblumberg  Icon User is offline

  • member icon


Reputation: 4232
  • View blog
  • Posts: 13,281
  • Joined: 25-December 09

Re: Returning a char array from function

Posted 18 January 2013 - 10:17 AM

First you can't use printf() to print a C++ string. This C function doesn't know anything about C++ classes. So you will need to convert your string to a C-string in order to use printf().

But the primary question is why are you using the very dangerous function gets() in the first place. Never try to retrieve user input into a C-string with a function that doesn't limit the number of characters you can supply.

For a C++ program you really should start using the C++ streams instead of scanf() and printf() in my opinion C++ streams are much less error prone.

If you remove or correct your printf() you will find that your function is correct. You can assign a C-string to a std::string. But remember the reverse doesn't work, you can't assign a std::string to a C-string. You can also return a std::string from your function as you are doing.

If you really want to stick with the C-string then I suggest you change your function so that you can pass the C-string into your function as a parameter. Then just use the proper input function to retrieve your string in the function. After all any chages you make to this paramter will not be lost when the function returns.

#include <iostream>
#include <iomanip>
#include <cstdio>

using namespace std;

void getName(char buffer[], int Buffer_size)
{
   printf("What is the name of this hauler?");

   fgets(buffer, Buffer_size, stdin);
   // Or better yet
   cin.getline(buffer, Buffer_size);
   // or even, but never forget to set the size with a call to setw().
   cin >> setw(Buffer_size) >> buffer;
   printf("%s", buffer);
}





Jim
Was This Post Helpful? 1
  • +
  • -

#4 synlight  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 582
  • Joined: 14-September 11

Re: Returning a char array from function

Posted 18 January 2013 - 10:18 AM

I can't use cin and cout. We're not allowed. I wish I could. My professor has antiquated views. Here is the example from my professor that we are supposed to use all semester, or he will dock us 20 points and return our assignment for recoding:

double getDouble(char pr[])
{
double d;
char buffer[40];
printf("\n%s", pr);
gets(buffer);
d=atof(buffer);
return d;
}


It's very frustrating. I am graduating in May. My favorite part of that is never having to deal with this professor again. This is my 3rd class with him, and he makes me want to gouge my eyes out.

This post has been edited by synlight: 18 January 2013 - 10:20 AM

Was This Post Helpful? 0
  • +
  • -

#5 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3075
  • Posts: 10,783
  • Joined: 08-August 08

Re: Returning a char array from function

Posted 18 January 2013 - 10:18 AM

This:
string getName()
{
	char buffer[50];
	string name;
	
	printf("What is the name of this hauler?");
	
	gets(buffer);
	name = buffer;
	
	printf("%s\n", name.c_str());
	
	return name;
}

int main(int argc, const char * argv[])
{
	string nm;
	nm = getName();
	printf("Name: %s\n",nm.c_str());

	return 0;
}


got this output on my system:
warning: this program uses gets(), which is unsafe.
What is the name of this hauler?someone
someone
Name: someone


This post has been edited by CTphpnwb: 18 January 2013 - 10:21 AM

Was This Post Helpful? 1
  • +
  • -

#6 synlight  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 582
  • Joined: 14-September 11

Re: Returning a char array from function

Posted 18 January 2013 - 10:24 AM

Thanks you guys. Please remember this post and my crazy professor as I beg for help this semester. I like to solve my own problems, and only post here as a last resort. I can figure things out when I have normal rules to follow.

It's gonna be a looooong 4 months.

ETA: converting it to a C String worked beautifully, Jim and CT. I really appreciate the help.

This post has been edited by synlight: 18 January 2013 - 10:29 AM

Was This Post Helpful? 0
  • +
  • -

#7 jimblumberg  Icon User is offline

  • member icon


Reputation: 4232
  • View blog
  • Posts: 13,281
  • Joined: 25-December 09

Re: Returning a char array from function

Posted 18 January 2013 - 10:30 AM

If you're not allowed to use cin and cout then I doubt that you will be able to use std::string. Your code sample looks more like C (although very poor C) than C++ so you should probably stick with using C.

Jim
Was This Post Helpful? 0
  • +
  • -

#8 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5901
  • View blog
  • Posts: 12,806
  • Joined: 16-October 07

Re: Returning a char array from function

Posted 18 January 2013 - 11:09 AM

While it's a silly thing to do, given the brain dead requirements, this should work:
string getName() {
	char buffer[50];
	printf("What is the name of this hauler?\n");
	return string(fgets(buffer, sizeof(buffer), stdin));
}



Note, even though you'd doing C in C++, you still should never use gets. Also, your printf should looks something like:
string name = getName();
printf("name = %s\n", name.c_str());



You really shouldn't have been able to compile a printf with a std::string.
Was This Post Helpful? 1
  • +
  • -

#9 undefined behaviour  Icon User is offline

  • New D.I.C Head

Reputation: 7
  • View blog
  • Posts: 36
  • Joined: 17-January 13

Re: Returning a char array from function

Posted 18 January 2013 - 07:31 PM

It seems to me as though your professor might want you to return the string as an array of chars, rather than converting the array of chars to a string. fgets already solves this problem in just one line. Wrap it.

This might require some arguing with stupid professors. If their assignment explicitly states that you can't use arguments as storage for output then you can't use this. Otherwise logic would dictate that you are on a journey to solve the problem your own way. There are obvious benefits that you can argue are good practises:
1. The C standard is full of consistency in this regards. Look at fgets, snprintf, strchr, etc, etc... Even gets in your example, will expect input in order to store the output.
2. This design philosophy lends itself better to modularity. Some problems are better solved by using automatically managed memory. Why use something that forces you to develop complex, inefficient and unsuitable alternatives to an otherwise simple algorithm?
Was This Post Helpful? 0
  • +
  • -

#10 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1102
  • View blog
  • Posts: 4,597
  • Joined: 09-June 09

Re: Returning a char array from function

Posted 18 January 2013 - 10:56 PM

Quote

It seems to me as though your professor might want you to return the string as an array of chars, rather than converting the array of chars to a string. fgets already solves this problem in just one line.

Returning a pointer to an array of characters on the stack directly will result in undefined behavior. I believe the C++ string requirement was to prevent the use of dynamic memory allocation.

This post has been edited by jjl: 18 January 2013 - 11:08 PM

Was This Post Helpful? 0
  • +
  • -

#11 undefined behaviour  Icon User is offline

  • New D.I.C Head

Reputation: 7
  • View blog
  • Posts: 36
  • Joined: 17-January 13

Re: Returning a char array from function

Posted 20 January 2013 - 08:18 PM

View Postjjl, on 18 January 2013 - 10:56 PM, said:

Quote

It seems to me as though your professor might want you to return the string as an array of chars, rather than converting the array of chars to a string. fgets already solves this problem in just one line.

Returning a pointer to an array of characters on the stack directly will result in undefined behavior. I believe the C++ string requirement was to prevent the use of dynamic memory allocation.


Please explain how the following will result in undefined behaviour:
int main(void) {
    char foo[512];
    char *bar = fgets(foo, sizeof foo, stdin);
}


This renders the following statement invalid: "Returning a pointer to an array of characters on the stack directly will result in undefined behavior."

I suggest reading posts carefully before you comment on them.
Was This Post Helpful? 0
  • +
  • -

#12 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3075
  • Posts: 10,783
  • Joined: 08-August 08

Re: Returning a char array from function

Posted 20 January 2013 - 09:16 PM

I believe this demonstrates what jjl was saying:
char *mygets(int n) {
	char ar[3] = {"12"};
	char *rtrn;
	rtrn = &ar[n];
	return rtrn;
}

char ar2[3] = {"12"};

char *another_gets(int n) {
	char *rtrn;
	rtrn = &ar2[n];
	return rtrn;
}
int main(int argc, const char * argv[])
{
	char *ptr = mygets(1);
	char *ptr2 = another_gets(1);
	cout << "ptr: " << ptr << " ptr2: " << ptr2 << endl;
	return 0;
}


ptr2 is valid because ar2 is not on the stack. It would also be valid if ar2 were on the stack but in the scope of main().
Was This Post Helpful? 0
  • +
  • -

#13 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1102
  • View blog
  • Posts: 4,597
  • Joined: 09-June 09

Re: Returning a char array from function

Posted 20 January 2013 - 11:10 PM

Quote

Please explain how the following will result in undefined behaviour:
int main(void) {
    char foo[512];
    char *bar = fgets(foo, sizeof foo, stdin);
}



It would of been more accurate for me to say, returning a pointer to memory that is allocated in the called function's stack frame will result in undefined behavior.
Was This Post Helpful? 0
  • +
  • -

#14 undefined behaviour  Icon User is offline

  • New D.I.C Head

Reputation: 7
  • View blog
  • Posts: 36
  • Joined: 17-January 13

Re: Returning a char array from function

Posted 21 January 2013 - 03:38 AM

View Postjjl, on 20 January 2013 - 11:10 PM, said:

Quote

Please explain how the following will result in undefined behaviour:
int main(void) {
    char foo[512];
    char *bar = fgets(foo, sizeof foo, stdin);
}



It would of been more accurate for me to say, returning a pointer to memory that is allocated in the called function's stack frame will result in undefined behavior.


Please read post #9 carefully and tell me where I encouraged using memory local to the function. To the contrary, I said "fgets already solves this problem in just one line" and "If their assignment explicitly states that you can't use arguments as storage for output then you can't use this". Am I to humour your misunderstanding? Please show me where in the C or C++ standard any mention of a "stack frame" is. Can I call it a "graph frame", given the mainstream implementation of concurrency and synchronisation these days, instead?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1