函数在 C 中不返回任何内容
Function is not returning anything in C
我正在尝试 return C 程序中的字符串。该程序是一个罗马数字编码器,采用整数和 returns 字符串作为罗马数字:
#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;
}
指针没有return任何东西
char res[]
是函数的局部变量,退出函数后它会超出范围。
两个问题:
- 您的字符串太短。它实际上只有 1 个字节长,并且只容纳空终止符。
- 自动存储变量,函数returns时不存在。
- 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;
}
改用strcpy,使用更大的字符串(你可以进行动态内存分配)
我正在尝试 return C 程序中的字符串。该程序是一个罗马数字编码器,采用整数和 returns 字符串作为罗马数字:
#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;
}
指针没有return任何东西
char res[]
是函数的局部变量,退出函数后它会超出范围。
两个问题:
- 您的字符串太短。它实际上只有 1 个字节长,并且只容纳空终止符。
- 自动存储变量,函数returns时不存在。
- 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;
}
改用strcpy,使用更大的字符串(你可以进行动态内存分配)