从C中的函数返回char

0 c arduino

我已经尝试了所有Google的能力,但似乎无法解决这个问题.我正在尝试返回一个字符并传递给另一个没有运气的函数.我需要做某种内存位置吗?

char hostname[] = "www.XXXXX.com";
uint8 ipaddr[]  = {XXX,XXX,XXX,XXX};
char uri[]      = "/api/Login/";  
char key[] = API_KEY;  //3490324032-asdfasd-234234
const int port  = 80;

//function to combine uri and key
char combine(char key[], char uri[]) {
  int i = 0;
  int x = 0;
  char long_s[sizeof(uri) + sizeof(key)];

  while(uri[i]) {
      long_s[i] = uri[i];
      ++i;
  }
  while(key[x]) {
      long_s[i] = key[x];
      ++i;
      ++x;
  }
  long_s[i] = '\0';
  //Serial.print(long_s);
  return long_s;  //pointer?
} 

char lon = combine (key, uri);
char* newURI = &lon;

// A get request
GETrequest getSession(ipaddr, port, hostname, newURI);
Run Code Online (Sandbox Code Playgroud)

Wil*_*l A 6

combine上面的函数声称返回一个char,但实际上return long_s是在此行怀疑后返回char*作为注释.但是,更改函数以返回char*将不会真正让你在任何地方,因为返回堆栈上的字符串(char数组)的地址是一个危险的游戏 - 一旦函数返回,你不能依赖此指针有效.最好是将第三个参数组合起来,char result[]放入结果,或者返回malloc的char数组,并确保在某些时候释放().


caf*_*caf 5

你的函数的返回值是char-这意味着它返回一个单一 char(只能代表一个字符).字符串由chars 数组表示,通常由指针(char *)引用.

所以你需要返回char *- 但这会导致另一个问题.指针必须指向一个比函数调用更长的数组.long_s函数返回后,您的数组将被销毁,因此这不合适.通常的替代方法是允许调用者提供足够大小的缓冲区(还要注意您的循环可以用strcpy()strcat()函数替换):

char *combine(char result[], size_t result_sz, const char key[], const char uri[])
{
  /* Test to see if there is sufficient space */

  if (strlen(uri) + strlen(key) + 1 > result_sz)
  {
    return NULL;
  }

  strcpy(result, uri);
  strcat(result, key);

  return result;
} 
Run Code Online (Sandbox Code Playgroud)

然后你的来电者必须使用:

char lon[1024];
char *newURI = combine (lon, sizeof lon, key, uri);

if (newURI == NULL)
{
    /* Error - URL too long */
}
else
{
    GETrequest getSession(ipaddr, port, hostname, newURI);
}
Run Code Online (Sandbox Code Playgroud)