8 Replies - 766 Views - Last Post: 31 August 2011 - 07:21 AM Rate Topic: -----

#1 hulla  Icon User is offline

  • Writing Lines


Reputation: 49
  • View blog
  • Posts: 732
  • Joined: 05-March 11

Char array in class is not returning/printing to screen.

Posted 30 August 2011 - 03:09 AM

I have this class called Shape. It has a static function called help that does not take any parameters and returns type char. The code compiles fine and runs but when it is supposed to print the c-string, it does nothing.

It is possible to return a c-style string, right?

Here is a part of my code . . .
#include <iostream>
#include <windows.h>
#include <cassert>
using namespace std;


class Shape
{
private:
    double m_Length, m_Width, m_Height;
public:
    void setDimensions(double dLength, double dWidth, double dHeight)
    {
        m_Length = dLength;
        m_Width = dWidth;
        m_Height = dHeight;
    }
    static char help()
    {
        char helpMessage[]{"Test . . .\0"};
        return helpMessage[11];
    }
    double shapeSurfArea() { return (4*m_Height*m_Width)+(2*m_Length*m_Width); }
    double shapeVolume() { return m_Height*m_Length*m_Width; }
    double shapeLength() { return m_Length; }
    double shapeWidth() { return m_Width; }
    double shapeHeight() { return m_Height; }
    // Constructors
    Shape() { setDimensions(0, 0, 0); }
    Shape(double dLength, double dWidth, double dHeight) { setDimensions(dLength, dWidth, dHeight); }
};


int main()
{
    Shape cube(2,2,2);
    cout << Shape::help()      << endl;
    cout << cube.shapeVolume() << endl;
    cube.setDimensions(3, 6, 1);
    cout << cube.shapeVolume() << endl;
    return 0;
}



( @Nick, I included white-space this time :) )

This post has been edited by hulla: 30 August 2011 - 03:09 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Char array in class is not returning/printing to screen.

#2 PlasticineGuy  Icon User is offline

  • mov dword[esp+eax],0
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,436
  • Joined: 03-January 10

Re: Char array in class is not returning/printing to screen.

Posted 30 August 2011 - 03:18 AM

static char help()
You're returning a single character. You want a pointer to a character.
More importantly:
return helpMessage[11];
Here you return the 11th element of helpMessage, not the string itself. The 11th element is in fact a \0, which cout interprets as an empty string. Try:
return helpMessage;

Was This Post Helpful? 0
  • +
  • -

#3 Salem_c  Icon User is online

  • void main'ers are DOOMED
  • member icon

Reputation: 1743
  • View blog
  • Posts: 3,360
  • Joined: 30-May 10

Re: Char array in class is not returning/printing to screen.

Posted 30 August 2011 - 03:21 AM

18	    static char help()
19	    {
20	        char helpMessage[]{"Test . . .\0"};
21	        return helpMessage[11];
22	    }


You're not returning a string, you're returning a single char.
What is more, that char is out of bounds of your array.

Try something like
static std::string help()
{
   std::string helpMessage = "Test . . .";
   return helpMessage;
}



This is C++, you should stay away from char arrays for strings as much as possible.

@PlasticineGuy
Note that simply returning an array name results in returning a pointer to a local variable.
When the function returns, the variable is out of scope, and the pointer is then invalid.
Was This Post Helpful? 2
  • +
  • -

#4 PlasticineGuy  Icon User is offline

  • mov dword[esp+eax],0
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,436
  • Joined: 03-January 10

Re: Char array in class is not returning/printing to screen.

Posted 30 August 2011 - 03:32 AM

Right; I forgot.
Note also that 11th is not in fact out of bounds -- it is the \0 at the end.
Finally, just do:
return "Test . . .\0";
That way you don't even have to create a local string.
Was This Post Helpful? 0
  • +
  • -

#5 Salem_c  Icon User is online

  • void main'ers are DOOMED
  • member icon

Reputation: 1743
  • View blog
  • Posts: 3,360
  • Joined: 30-May 10

Re: Char array in class is not returning/printing to screen.

Posted 30 August 2011 - 04:34 AM

> Note also that 11th is not in fact out of bounds -- it is the \0 at the end.
There are 11 characters including the \0, which makes the subscripts 0 to 10 inclusive.
Was This Post Helpful? 0
  • +
  • -

#6 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Char array in class is not returning/printing to screen.

Posted 30 August 2011 - 07:10 AM

Generally speaking in terms of C you don't really "return strings" using the "return" statement. I suppose there are times when it happens but usually this is not the way things go. The reason is because you get into the problem of: who owns/manages the memory.

A C-str is a pointer to a char array. So when you do this:

char* returnStr() {
    char array[] = "Whatever"; //note the \0 is added by the compiler no need to add it.
    return array;
}


the problem here is that the array is a local variable to the function and does not exist past the end of the function. So when I "return" it that pointer now points to some block of memory (probably on the stack) that is no longer valid. Using it will probably cause my program to crash horribly or at the very least display garbage from the stack.

now I can do something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* returnStr() {
    char *retval = (char*)malloc(9);
    if (retval) {
        strcpy(retval, "whatever");
    }    
    return retval;
}

int main() {
    char* str = returnStr();
    if (str) {
        printf("%s", str);
        free(str);
    }
    
    return 0;
}


By using malloc I allocate memory out on the stack for our string. Great. But now our calling function is responsible for cleaning up the memory and experience tells us that this is a memory leak waiting to happen. It is better to allocate and free the memory all within one function, that way the programmer who allocates the memory has ensured that it gets cleaned up too.

There are of course other ways, such as returning a reference to a static array, problem there is that each time you call "returnStr" you would change the contents of the string -- not a really big deal so long as you document that *feature*.

You could return a const char* to a literal. This is actually fairly common since the literal will be stored in the program's static data. However we must return a const.

The more normal pattern is let the calling function allocate the memory and you just copy the string to it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* returnStr(char* arg) {
    if (arg) {
        strcpy(arg, "whatever");
    }    
    return arg;
}

int main() {
    char buffer[100];
    char* str = returnStr(buffer);
    printf("%s\nbuffer: %s", str, buffer);    
    return 0;
}

Was This Post Helpful? 1
  • +
  • -

#7 hulla  Icon User is offline

  • Writing Lines


Reputation: 49
  • View blog
  • Posts: 732
  • Joined: 05-March 11

Re: Char array in class is not returning/printing to screen.

Posted 31 August 2011 - 05:12 AM

I don't want to use a string because if I send this class to you and expect you to take advantage of the help, you would have to include the string header file.

The only solution I could think of was to use a char array but like Nick said, there is a problem with who owns the memory and memory on the stack is erased once the function ends.

@PlasticineGuy, Yeah this works fine . . .
    static char* help() { return "This class is for working with cubes and cuboids . . ."; }

but I get a warning saying . . .

Quote

warning: deprecated conversion from string constant to 'char*'|

Was This Post Helpful? 0
  • +
  • -

#8 Salem_c  Icon User is online

  • void main'ers are DOOMED
  • member icon

Reputation: 1743
  • View blog
  • Posts: 3,360
  • Joined: 30-May 10

Re: Char array in class is not returning/printing to screen.

Posted 31 August 2011 - 05:20 AM

It should be static const char* help()
Was This Post Helpful? 1
  • +
  • -

#9 hulla  Icon User is offline

  • Writing Lines


Reputation: 49
  • View blog
  • Posts: 732
  • Joined: 05-March 11

Re: Char array in class is not returning/printing to screen.

Posted 31 August 2011 - 07:21 AM

Oh thanks :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1