我正在使用 C 编写 BCD(二进制编码的十进制)并负责编写不同的 bcd 函数。
我需要将一个整数 i 编码到大小为 n 的缓冲区 char *s 中。该函数在成功时返回 0,在溢出时返回 -1(编码 i 需要大于 n 的缓冲区)。
函数如下:int bcd_encode(int i, int n, char *s)
和示例输入:assert(bcd_encode(a, 128, s) == 0);
我正在为函数 bcd_encode 编写代码,如果我错了,请纠正我,但我相信一个函数,并且只相信一个函数,如果你有一些 func(char x[])
和 char func(char *x)
它们是同一回事吗?所以你可以把它们都看成一个字符数组。如果它在函数定义之外,char x[];
将是一个 char 数组,而 char *x;
将是一个指针。
int bcd_encode(int i, int n, char *s){
int j = 0;
s = itoa(i, s, n+1);
}
但是这会返回一个警告“赋值从整数生成指针而不进行强制转换”和一个未定义的 itoa 符号。我尝试了一些不同的变体
*s = itoa(i); s = itoa(i); s = itoa(i, s, n+1);
如有任何帮助,我们将不胜感激。提前致谢!
最佳答案
你说:
... and correct me if I am wrong but I believe in a function and only in a function if you were to have some func(char x[]) and char func(char *x) they would be the same thing? So you can look at both of them as a char array. If it were outside the function definition char x[]; would be an char array and char *x; would be a pointer.
最好将它们都视为函数内部的指针(而不是都视为数组),但你已经捕获了关键点 - 在函数参数列表中,数组和指针之间的区别是模糊的,但其他地方的指针和数组不同。
在代码中,自 itoa()
假设在没有相反信息的情况下返回一个整数,您不能将其存储在指针中或作为指针(不使用大锤转换,这会使您的代码损坏)。
什么是itoa()
返回?它不是标准的 C 函数(例如,不在 ISO/IEC 9899:1999 中,也不在 POSIX 中)。 Wikipedia建议它不返回任何值,所以你不应该在任何地方分配它的值。 Linux在 <stdlib.h>
中将其作为非标准扩展使用不同的接口(interface)返回 char *
(这是它的第二个参数的值)。您可以安全地忽略返回值;事实上,您也可以进行赋值(在包含标题之后),但赋值是空操作。你需要知道这个函数是非标准的,它有多种定义,因此你必须知道什么对你的平台是正确的,或者避免使用它(也许使用 snprintf()
代替)。
引用链接的 Linux 手册页:
char* itoa (int __val, char * __s, int __radix)
Convert an integer to a string.
The function itoa() converts the integer value from val into an ASCII representation that will be stored under s. The caller is responsible for providing sufficient storage in s.
Note:
The minimal size of the buffer s depends on the choice of radix. For example, if the radix is 2 (binary), you need to supply a buffer with a minimal length of 8 * sizeof (int) + 1 characters, i.e. one character for each bit plus one for the string terminator. Using a larger radix will require a smaller minimal buffer size. Warning:
If the buffer is too small, you risk a buffer overflow. Conversion is done using the radix as base, which may be a number between 2 (binary conversion) and up to 36. If radix is greater than 10, the next digit after '9' will be the letter 'a'.If radix is 10 and val is negative, a minus sign will be prepended.
The itoa() function returns the pointer passed as s.
您不想使用 n+1
作为基数。
关于c - 使用 itoa() 结果为 : "assignment makes pointer from integer without a cast",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4928461/