[prog] simple c++ question

Laurel Fan laurel at sdf.lonestar.org
Sun Jun 22 17:43:33 EST 2003


On Sun, Jun 22, 2003 at 03:25:00PM -0700, Laura OConnor wrote:
> This is a simplified version of what I am trying to do:
>  
> #include <iostream>
> #inlcude <cstring>
>  
> using namespace std;
>  
> void readText(char *text[])
> {
>    char tempText[50];

tempText is a local variable in the readText function, therefore, the
memory in tempText is allocated for you when the function is called,
and is deallocated for you when the function exits.

>    int j = 0;
>  
>    cout <<"Please enter a line of text";
>    cin.getline(tempText, 50)
>    text[j] = strtok(tempText, " ");

strtok returns a pointer into tempText, so you're setting text[0] to
point to memory that is local to the readText function.

>         //text[j] = "foo";    - this would work

This works because string constants, such as "foo" are statically
allocated (they live for the entire duration of the program), so "foo"
in readText is the same thing as "foo" in main.

>        //removed while loop to get rest of tokens for simplicity
> }
>  
> int main()
> {
>    char *words[100];
>    readText(words);

readText set words[0] to memory that is local to the readText
function.  Therefore, it is no longer valid in main().

>    cout << words[0];  //check the first element
>  
>   return 0;
> }

If you want to do it this way, you have essentially 2 choices:

1. allocate the memory in main() first, then, in readText, copy the
tokenized string into your preallocated array.

2. allocate the memory using malloc() in readText(), and set the
pointers to your allocated memory.

Note that if you use malloc() to allocate memory, you will have to use
free() so that you don't leak memory.

Let me know if this wasn't clear, or if you need more details;
pointers can be tricky.

-- 
laurel at sdf.lonestar.org
http://dreadnought.gorgorg.org


More information about the Programming mailing list