繁体   English   中英

Function 在 C 中没有返回任何东西

[英]Function is not returning anything in C

我试图在 C 程序中返回一个字符串。 该程序是一个罗马数字编码器,接受 integer 并返回一个罗马数字字符串:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *solution(int n);
int main() {
  printf("%s", solution(2253));
  return 0;
}
char *solution(int n) {
  char res[] = "";
  char *resPtr = res;
  while(n != 0)
  {
    if (n >= 1000)
    {
      strncat(res, "M", 1);
      n -= 1000;
    }
    ...
  }
  return resPtr;
}

指针不返回任何东西

两个问题:

  1. 你的字符串太短了。 它实际上只有 1 个字节长,并且只容纳 null 终止符。
  2. 自动存储变量,当function返回时不再存在。
  3. strncat 不会增加字符串。

例子:

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

const char *hundreds[] = {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
const char *tens[] = {"X", "XX",    "XXX",  "XL",   "L",        "LX",   "LXX",  "LXXX",     "XC",   };
const char *digits[] =  {"I","II","III","IV","V","VI","VII","VIII","IX"};


char *solution(int n);

int main() 
{
    char *p;
    printf("%s", p = solution(2253));
    free(p);
    return 0;
}



char *solution(int n) 
{
    char *resPtr = malloc(n / 1000 + 4 + 4 + 4 + 1);
    size_t pos = 0;
    if(resPtr)
    {
        while(n >= 1000)
        {
            resPtr[pos++] = 'M'; // no need of expensive strncat function
            n -= 1000;
        }
        if(n / 100)
        {
            strcpy(&resPtr[pos], hundreds[n / 100 - 1]);
            pos += strlen(hundreds[n / 100 - 1]);
            n = n % 100;
        }
        if(n / 10)
        {
            strcpy(&resPtr[pos], tens[n / 10 - 1]);
            pos += strlen(tens[n / 10 - 1]);
        }
        n = n % 10;
        if(n) strcpy(&resPtr[pos], digits[n - 1]);
    }
    return resPtr;
}

https://godbolt.org/z/1sadrb

char res[]是 function 的局部变量,退出 function 后它会从 scope 中消失。

改为使用 strcpy,使用更大的字符串(您可以使用 go 进行动态 memory 分配)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM