[英]How can I fix a pointer error in C?
我开始学习C语言中的指针。
如何解决函数x()
的错误?
这是错误:
Error: a value of type "char" cannot be assigned to an entity of type "char *".
这是完整的来源:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
void x(char **d, char s[]) {
d = s[0]; // here i have the problem
}
void main() {
char *p = NULL;
x(&p, "abc");
}
在函数x()
,传递d
它是char **
(指向字符串指针的指针))和char s[]
( char
的数组,类似于传递给char
的指针)。
所以在这一行:
d = s[0];
s[0]
是一个char
,而char **d
是一个指向char
的指针。 这些是不同的,编译器说您不能从一个分配到另一个。
但是,您的编译器是否确实向您发出以下警告?
Error: a value of type "char" cannot be assigned to an entity of type "char *"
给定代码示例,它应该在末尾说char **
。
我认为您正在尝试使x
做的是将作为第二个参数传递的字符串的地址复制到第一个指针中。 那将是:
void x(char **d, char *s)
{
*d = s;
}
这使调用者中的p
指向常量xyz
字符串,但不复制内容。
如果要复制字符串的内容,请执行以下操作:
void x(char **d, char *s)
{
*d = strdup(s);
}
并确保您记得在main()
中将free()
返回值,以及在顶部添加#include <string.h>
。
这是您可以执行的操作,因此它将编译为两个版本。
版本1。
void x(char **d, char s[]) {
d = (char**)s[0];
}
或版本2。
void x(char **d, char *s) {
*d = s;
}
希望这可以帮助。
一种更合适的方法是使用strcpy
:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
void x(char **d) {
*d = malloc(4 * sizeof(char));
strcpy(*d, "abc");
}
int main() {
char *p;
x(&p);
printf("%s", p);
free(p);
return 0;
}
输出:abc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.