gpt4 book ai didi

c - 如何修复 C 中的指针错误?

转载 作者:太空宇宙 更新时间:2023-11-04 04:44:53 25 4
gpt4 key购买 nike

我开始学习 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 do 是将作为第二个参数传递的字符串的地址复制到第一个指针中。那将是:

void x(char **d, char *s)
{
*d = s;
}

这使得 p在调用者中指向常量 xyz字符串但不复制内容。

如果这个想法是复制字符串的内容:

void x(char **d, char *s)
{
*d = strdup(s);
}

并确保您记得free() main() 中的返回值, 以及添加 #include <string.h>在顶部。

关于c - 如何修复 C 中的指针错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22234382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com