[英]C programming: pass long integer to function and return a string
C 编程:我需要将很长的 integer (N) 传递给 function 并返回一个单词(字符串),将值转换为“有效”或“正确有效” 代码不起作用是因为我需要使用指针吗? 您能否告知我应该如何修改代码以及为什么?
#include <stdio.h>
int digitmatch(long N); // function to match the first two digits of the card
int isvalid(long N);
int main()
{
long N;
N = 5212888888881881;
printf("\n digit match: %d",digitmatch(N));
printf("\n validity: %s",isvalid(N));
}
int digitmatch(long N)
{
long digit;
digit = N;
while (digit >= 100)
{
digit /= 10;
}
return digit;
}
char isvalid(long N)
{
char valid[20];
if (digitmatch(N) == 51 || digitmatch(N) == 52)
{
valid = "MasterCard";
}
else
{
valid = "invalid";
}
return valid;
}
非常感谢
在 C 语言中,字符串按照惯例是 null 终止的字符数组。 char
只是一个字符或字节。 因此,您希望isvalid
返回的不是字符,而是字符串。
但是 arrays 不是第一个 class 对象,并且 function 不能返回数组,程序员也不能分配给数组。 您只能返回数组第一个元素上的指针或将其分配给另一个指针。 但这会导致下一个问题,因为在 function 中声明的自动对象在 function 返回时达到其生命周期的终点。
在您的情况下,您可以为返回的字符串声明 2 static (const) arrays:
char* isvalid(long N); // initial declaration must match the definition...
...
const char* isvalid(long N)
{
static char master[] = "MasterCard";// static arrays won't reach end of life at return
static char invalid[] = "invalid";
const char *valid;
if (digitmatch(N) == 51 || digitmatch(N) == 52)
{
valid = master;
}
else
{
valid = invalid;
}
return valid;
}
const
在这里用于通知调用者它不应该通过返回的指针更改任何内容。
在 C 中,字符串的类型为const char*
或char*
,因此您的 function 应该返回:
const char* isvalid(long N)
{
if (digitmatch(N) == 51 || digitmatch(N) == 52)
{
return "MasterCard";
}
else
{
return "invalid";
}
}
看到这个:
#include <stdio.h>
const char* fun(); //return pointer to string
int main()
{
printf("%s",fun());
return 0;
}
const char* fun()
{
const char *ret = "Hello! World"; //This string is not placed in stack it is placed in .rodata, So it is not destroyed upon function return.
return ret;
}
在你的情况下:
const char* isvalid(long N)
{
if (digitmatch(N) == 51 || digitmatch(N) == 52)
{
return "MasterCard";
}
else
{
return "invalid";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.