Funxtion returning a pointer to an array.

Dear members,

I'm trying to write a function that returns a pointer to an array. I read some older topic on the forum here, to try to find my way, but it does not seem to work.

What I try to do:
I have a character array, containing an ip address, and I want it in an array of 4 integer values.

This is the piece of code I wrote:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <string.h>
#include <stdlib.h>

using namespace std;

int *CharToArray (char data[]) {

    int octet[4];
    char tmp[3];
    int *pointer = octet;
    int cnt = 0;
    int idx = 0;

    //pointer = octet;

    for (int i=0; i<16; i++) {
        if (data[i] == '.' or data[i] == '\0') {
            octet[idx] = atoi(tmp);
            idx++;
            cnt = 0;
            strcpy(tmp, "");
        } else {
            tmp[cnt] = data[i];
            cnt++;
        }
    }

    for (int i=0; i<4; i++) {
        cout << octet[i] << endl;
    }

    cout << endl;

    return pointer;
}

int main (void) {
    cout << "Start.." << endl;

    char ipAddress[16] = "192.168.100.200";

    int *result = CharToArray(ipAddress);

    for (int i=0; i<4; i++) {
        cout << result[i] << endl;
    }

    return 0;
}


And this is what I get, when I run it:


Start..
192
168
100
200

192
9510900
0
0

Press ENTER to continue.



I would expect to see twice the same output. but only the first byte of the ip address seems to be correct, and the second byte is each time a different value when I run the code.

Can you give me a hint on what I'm doing wrong here?


Thanks a lot!
--
Wim
Anything created without the new (or malloc) keyword is created on the memory known as the stack. This includes the array created here:

int octet[4];

When a function is called, a region of the stack is set aside for it to use. Anything created inside that function (without using new) is created in that part of the stack. When the function ends, that part of the stack becomes available for use by something else.

So, the memory that is your array:
int octet[4];
becomes available for use when the function finishes. Clearly, something is using that memory and writing over your array. You still have a pointer to the right bit of memory - it's just being used by something else.

To get round this, either create the array outside the function and pass in a pointer to it, or create it using new (don't forget to delete when you're done with it).
Last edited on
Thanks Moshops!

This memory thing is quite new for me!

I did:

1
2
int *octet;
octet = new int[4];


In my function, which did the trick. Thanks a lot for the hint and the solution!

Cheers!
Wim
Topic archived. No new replies allowed.