-1

I'm working on returning a char from a function. Everything works fine when I get these weird symbols on the screen.

#include <iostream>

void testfunc(char* outStr);

int main()
{
  char FirstName[10];
  testfunc(FirstName);
  std::cout << "So far so good.";
  std::cout << std::endl;
  std::cout << FirstName;
  std::cout << std::endl;
  std::cout << "It worked!";
  std::cout << std::endl;
  system("pause");
  return 0;
}

void testfunc(char* outStr)
{
  char FirstName[10];
  std::cin >> FirstName; 
  outStr = FirstName;
}

I have a picture of the problem but it seems I can't post any. the output looks like random bloks followed by numbers and symbols. It's not an address. It does compile and run through the program fine. the cout's before and after FirstName, all output just fine. FirstName itself, however, outputs symbols and blocks.

luk27R
  • 1
  • 1
  • 1
    `outStr = FirstName` only copies the direction. use `strcpy(outStr, FirstName)`. Or better yet, use `std::string` – Noel Dec 01 '14 at 19:51
  • I don't think this is a duplicate of that particular question; the offending line is `outStr = FirstName` which appears to be an attempt to *copy* the array contents. – cdhowie Dec 01 '14 at 19:51
  • 1
    1. The `FirstName` array in `testfunc()` gets invalid as soon the function returns. 2. `outStr = FirstName;` is actually useless, it doesn't change the `char FirstName[10];` declared in `main()` (hint, try `strncpy()` instead of `=`!) – πάντα ῥεῖ Dec 01 '14 at 19:53

1 Answers1

3

outStr = FirstName doesn't actually copy the string, it just assigns the outStr parameter variable to point to the first element of the FirstName array within testfunc(); the FirstName array within main() is not modified.

Either use strcpy() to copy the string, or (better yet) use std::string instead of character arrays.

cdhowie
  • 158,093
  • 24
  • 286
  • 300