0

I want you to look at the following two codes and tell me why the first one works and the other one doesn't.

First Code (Working):

#include <iostream>
#include <string.h>

using namespace std;

char* getCoordinates(char* AndroidID)
{//Access the database and get the South Latitude value
    //This is here is dummy data for testing
    const char* S = "27.19122859";
    const char* N = "27.19245011";
    const char* W = "31.17657602";
    const char* E = "31.17657602";
    char X[100]="";
    strncat(X, "S", 1);
    strncat(X, S, strlen(S));
    strncat(X, "N", 1);
    strncat(X, N, strlen(N));
    strncat(X, "W", 1);
    strncat(X, W, strlen(W));
    strncat(X, "E", 1);
    strncat(X, E, strlen(E));
    char* Y = X;
    cout<<Y;
    return Y;
}
int main()
{
    char* sda=NULL;
    getCoordinates(sda);
    return 0;
}

This prints out correctly the string I want to compose

S27.19122859N27.19245011W31.17657602E31.17657602

But when I try to do the same thing but print out the return value in main() things get a little weird Second Code (Not working)

#include <iostream>
#include <string.h>

using namespace std;

char* getCoordinates(char* AndroidID)
{//Access the database and get the South Latitude value
    //This is here is dummy data for testing
    const char* S = "27.19122859";
    const char* N = "27.19245011";
    const char* W = "31.17657602";
    const char* E = "31.17657602";
    char X[100]="";
    strncat(X, "S", 1);
    strncat(X, S, strlen(S));
    strncat(X, "N", 1);
    strncat(X, N, strlen(N));
    strncat(X, "W", 1);
    strncat(X, W, strlen(W));
    strncat(X, "E", 1);
    strncat(X, E, strlen(E));
    char* Y = X;
    return Y;
}

int main()
{
    char* sda=NULL;
    char* T=getCoordinates(sda);
    cout<<T;
    return 0;
}

This outputs:

S27. N27.19245011W31.`%@ \╞G ░■) $âG @■)

What is the problem here?

2 Answers2

1

You are returning a pointer to an array of char which has lifetime only as long as the function. When the function returns the array is no longer valid.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

It dos not work because your function getCoordinates return pointer to buffer which has local scope of function getCoordinates and gets destroyed after the functions returns. Use std::string instead of char and it will be working.

Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148