简体   繁体   English

如何解决C中的指针错误?

[英]How can I fix a pointer error in C?

I am starting to learn about pointers in C. 我开始学习C语言中的指针。

How can I fix the error that I have in function x() ? 如何解决函数x()的错误?

This is the error: 这是错误:

Error: a value of type "char" cannot be assigned to an entity of type "char *".

This is the full source: 这是完整的来源:

#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");
}

In function x() you pass d which is a char ** (a pointer to a string pointer), and char s[] (an array of char , passed as similarly to a pointer to char ). 在函数x() ,传递d它是char ** (指向字符串指针的指针))和char s[]char的数组,类似于传递给char的指针)。

So in the line: 所以在这一行:

d = s[0];

s[0] is a char , whereas char **d is a pointer to a pointer to char . s[0]是一个char ,而char **d是一个指向char的指针。 These are different, and the compiler is saying you cannot assign from one to the other. 这些是不同的,编译器说您不能从一个分配到另一个。

However, did your compiler really warn you as follows? 但是,您的编译器是否确实向您发出以下警告?

Error: a value of type "char" cannot be assigned to an entity of type "char *"

Given the code sample, it should have said char ** at the end. 给定代码示例,它应该在末尾说char **

I think what you are trying to make x do is copy the address of the string passed as the second argument into the first pointer. 认为您正在尝试使x做的是将作为第二个参数传递的字符串的地址复制到第一个指针中。 That would be: 那将是:

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

That makes p in the caller point to the constant xyz string but does not copy the contents. 这使调用者中的p指向常量xyz字符串,但不复制内容。

If the idea was to copy the string's contents: 如果要复制字符串的内容,请执行以下操作:

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

and ensure you remember to free() the return value in main() , as well as adding #include <string.h> at the top. 并确保您记得在main()中将free()返回值,以及在顶部添加#include <string.h>

Here's what you can do, so it would compile in two versions. 这是您可以执行的操作,因此它将编译为两个版本。

Version 1. 版本1。

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

or Version 2. 或版本2。

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

Hope this helps. 希望这可以帮助。

A more proper way would be to use strcpy : 一种更合适的方法是使用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;
}

Outputs: abc 输出:abc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM