gpt4 book ai didi

c++ - 为什么 cout 一个简单的 char* 不起作用?

转载 作者:行者123 更新时间:2023-11-28 02:05:59 25 4
gpt4 key购买 nike

<分区>

我希望您查看以下两段代码并告诉我为什么第一个有效而另一个无效。

第一个代码(工作):

#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;
}

这会正确打印出我要组成的字符串

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

但是当我尝试做同样的事情但在 main() 中打印出返回值时,事情变得有点奇怪第二个代码(不工作)

#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;
}

这个输出:

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

这里有什么问题?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com