我传递了一个指向函数的结构指针。我需要的是在主函数中获取字符串"连接被拒绝"(从ssh_get_error()返回)。
#include <libssh/libssh.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
typedef struct rtns {
bool state;
char* desc;
} rtns;
int connect_host(rtns *con_host) {
const char* desc;
char desc2[1000];
ssh_session my_ssh_session;
int rc;
my_ssh_session = ssh_new();
if (my_ssh_session == NULL)
exit(-1);
ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "localhost");
rc = ssh_connect(my_ssh_session);
if (rc != SSH_OK) {
(*con_host).state = false;
desc = ssh_get_error(my_ssh_session);
strcpy(desc2, ssh_get_error(my_ssh_session));
(*con_host).desc = strdup(desc2);
cout << "from connect_host function->" <<con_host->desc << "\n";
} else {
(*con_host).state = true;
}
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
}
int main() {
rtns con_host;
rtns *p = (rtns*) malloc(sizeof(struct rtns));
p = (rtns*) malloc(20);
connect_host(&con_host);
cout << "from main function->" << *(con_host.desc) << "\n\n";
}
输出 -
from connect_host function->Connection refused
from main function->C
问题是我只得到一个角色&#34; C&#34;在主要功能。我有一些想法,我正在做内存分配错误,但我不知道如何正确地做到这一点。我也尝试在con_host函数中移动malloc分配,但它也没有工作。
答案 0 :(得分:0)
想想你在打印什么。您传递给流char
,而不是char *
:
cout << "from main function->" << *(con_host.desc) << "\n\n";
// *(con_host.desc) = *(char *) = char
// Above is a simplification but you get the point.
只要con_host.desc
是一个空终止的c字符串,就可以像这样打印出来:
cout << "from main function->" << con_host.desc << "\n\n";
答案 1 :(得分:0)
这不是内存分配错误。它是由输出语句引起的。改为
onItemClick(AdapterView<?> parent, View view, int position, long id)