[英]incompatible pointer types passing 'char (*)[128]' to parameter of type 'char **'
I can't figure out why does the following code generates this error: 我不知道为什么以下代码会产生此错误:
incompatible pointer types passing 'char (*)[128]' to parameter of type 'char **'
int main(int argc, char *argv)
{
char line[128];
size_t n;
FILE *fp = fopen(argv[1], "r");
if (NULL == fp)
{
log_error("%d. %s", errno, strerror(errno));
exit(EXIT_FAILURE);
}
while(-1 != getline(&line, &n, fp))
{
// do something
}
return 0;
}
The error is generated by the following line -1 != getline(&line, &n, fp)
Here is the prototype for getline,
错误是由以下行
-1 != getline(&line, &n, fp)
产生的-1 != getline(&line, &n, fp)
这是getline,
的原型getline,
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
What am I doing wrong? 我究竟做错了什么?
getline
will allocate a buffer for you (that you should free when you are finished with it). getline
将为您分配一个缓冲区(完成后应释放该缓冲区)。 Instead of passing it a pointer to a statically allocated buffer, just pass it a pointer to a char *
. 与其传递一个指向静态分配的缓冲区的指针,不如传递一个指向
char *
的指针。 If the pointer is NULL, it'll allocate a new buffer and point you to it. 如果指针为NULL,它将分配一个新的缓冲区并指向您。 Changing
char line[128];
更改
char line[128];
to char *line = NULL;
到
char *line = NULL;
should do the trick; 应该做到这一点; just remember to free it when you're done with it.
只要记得在完成操作后将其释放即可。
From the man page: 从手册页:
If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program.
如果* lineptr为NULL,则getline()将分配用于存储行的缓冲区,该缓冲区应由用户程序释放。 (In this case, the value in *n is ignored.)
(在这种情况下,* n中的值将被忽略。)
Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc(3)-allocated buffer *n bytes in size.
另外,在调用getline()之前,* lineptr可以包含一个指向分配了malloc(3)的缓冲区的指针* n个字节。 If the buffer is not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary.
如果缓冲区的大小不足以容纳该行,则getline()使用realloc(3)调整其大小,并根据需要更新* lineptr和* n。
In either case, on a successful call, *lineptr and *n will be updated to reflect the buffer address and allocated size respectively.
无论哪种情况,在成功调用后,* lineptr和* n都会更新以分别反映缓冲区地址和分配的大小。
How it might look in your example main
function: 在示例
main
功能中的外观:
int main(int argc, char **argv)
{
char *line = NULL;
size_t n;
FILE *fp = fopen(argv[1], "r");
if (NULL == fp)
{
log_error("%d. %s", errno, strerror(errno));
exit(EXIT_FAILURE);
}
while(-1 != getline(&line, &n, fp))
{
// do something
}
free(line);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.