[英]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.