在 C 中传递 char 指针 [英] Passing char pointer in C
问题描述
好的,我正在尝试将 char 指针传递给另一个函数.我可以用一个 char 数组来做到这一点,但不能用一个 char 指针来做到这一点.问题是我不知道它的大小,所以我无法在 main()
函数中声明任何关于大小的内容.
Okay so I am trying to pass a char pointer to another function. I can do this with an array of a char but cannot do with a char pointer. Problem is I don't know the size of it so I cannot declare anything about the size within the main()
function.
#include <stdio.h>
void ptrch ( char * point) {
point = "asd";
}
int main() {
char * point;
ptrch(point);
printf("%s
", point);
return 0;
}
但这不起作用,这两个起作用:
This does not work however, these two works:
1)
#include <stdio.h>
int main() {
char * point;
point = "asd";
printf("%s
", point);
return 0;
}
2)
#include <stdio.h>
#include <string.h>
void ptrch ( char * point) {
strcpy(point, "asd");
}
int main() {
char point[10];
ptrch(point);
printf("%s
", point);
return 0;
}
所以我试图了解问题的原因和可能的解决方案
So I am trying to understand the reason and a possible solution for my problem
推荐答案
void ptrch ( char * point) {
point = "asd";
}
您的指针按值传递,此代码复制,然后覆盖副本.所以原来的指针是不变的.
Your pointer is passed by value, and this code copies, then overwrites the copy. So the original pointer is untouched.
附:需要注意的是,当您执行 point = "blah"
时,您正在创建一个字符串文字,任何 modify 的尝试都是 未定义的行为,所以它真的应该是 const char *
P.S. Point to be noted that when you do point = "blah"
you are creating a string literal, and any attempt to modify is Undefined behaviour, so it should really be const char *
修复 - 像@Hassan TM 那样传递一个指向指针的指针,或者如下所示返回指针.
To Fix - pass a pointer to a pointer as @Hassan TM does, or return the pointer as below.
const char *ptrch () {
return "asd";
}
...
const char* point = ptrch();
这篇关于在 C 中传递 char 指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!