提问人:auem 提问时间:10/11/2022 更新时间:10/11/2022 访问量:84
如何返回变量?
How to return variable?
问:
我正在编写一个程序,将字母转换为莫尔斯电码,然后将它们传输到 LED 并闪烁。我无法返回值“.- -...”
#include <stdio.h>
#include <string.h>
char *encode()
{
char *name = "AB";
char name_m[100] = "";
for (int i = 0; i < strlen(name); i++)
{
if (name[i] == 65)
{
strcat(name_m, ".- ");
}
else if (name[i] == 66)
{
strcat(name_m, "-...");
}
};
printf("%s", name_m);
return name_m;
}
int main()
{
char *name_m;
name_m = encode();
printf("\n%s", name_m);
}
main.c:22:10: warning: function returns address of local variable [-Wreturn-local-addr]
22 | return name_m;
| ^~~~~~
.- -...
(null)
答:
2赞
0___________
10/11/2022
#1
在 C 中,你不能返回对局部变量的引用(指针),因为当函数返回时,它就不再存在。
您需要将 te buffer 传递给函数:
char *encode(char *name_m, const char *name)
{
for (int i = 0; i < strlen(name); i++)
{
if (name[i] == 'A')
{
strcat(name_m, ".- ");
}
else if (name[i] == 'B')
{
strcat(name_m, "-...");
}
}
printf("%s", name_m);
return name_m;
}
动态分配它:
char *encode( const char *name)
{
char *name_m = malloc(100);
if(name_m)
{
for (int i = 0; i < strlen(name); i++)
{
if (name[i] == 'A')
{
strcat(name_m, ".- ");
}
else if (name[i] == 'B')
{
strcat(name_m, "-...");
}
}
printf("%s", name_m);
}
return name_m;
}
或最糟糕的解决方案 - 将其定义为静态
char *encode( const char *name)
{
static char name_m[100];
if(name_m)
{
for (int i = 0; i < strlen(name); i++)
{
if (name[i] == 'A')
{
strcat(name_m, ".- ");
}
else if (name[i] == 'B')
{
strcat(name_m, "-...");
}
}
printf("%s", name_m);
}
return name_m;
}
评论