如何越过一个指针和堆分配空间 [英] How to pass over a pointer and allocate space on heap
问题描述
我想传递一个字符指针的函数,然后用东西填满它,以便调用函数可以使用它即可。因为它总是给我怪异的东西在调用函数中我写了什么,我做了简单的重新presentation:
I am trying to deliver a char pointer to a function which then fills it with stuff so that the calling function could use it then. As it always gave me weird stuff in the calling function i wrote a simple representation about what I have done:
#include <stdio.h>
#include <stdlib.h>
void bla(char *t)
{
t = (char*) malloc(5);
if (t != 0) {
t[0] = 'h';
printf("%c\n", t[0]);
}
}
int main(int argc, char **argv)
{
char b[10];
bla(b);
printf("%c\n", b[0]);
return 1;
}
我不太确定是否有事可做了C经过论证的副本。我需要一个指针传递给一个指针则还是有一个更好的解决方案?
I'm not quite sure if it has something to do that C passes a copy of the argument. Do I need to pass a pointer to a pointer then or is there a better solution?
编辑:
对不起球员,但我没有得到它。能否请您过目这个例子:
Sorry guys but I didn't get it. Could you please look over this example:
#include <stdio.h>
#include <stdlib.h>
void blub(char **t)
{
printf("%d\n", *t);
*t = (char*) malloc(sizeof(char) * 5);
*t[0] = 'a';
*t[1] = 'b';
printf("%d\n", *t);
printf("%d\n", *t[0]);
printf("%d\n", *t[1]);
}
int main(int argc, char **argv)
{
char *a;
blub(&a);
printf("%d\n", a);
printf("%d\n", a[0]);
printf("%d\n", a[1]);
return 1;
}
输出如下所示:
./main
6154128
140488712
97
98
140488712
97
0 <== THIS SHOULD BE 98 AS ABOVE!?
为什么我得到的功能blafu 98和主要的它是一个空指针?我完全以困惑:/
Why do i get 98 in the function blafu and in main it is a null pointer?! I am totaly confused :/
推荐答案
您需要使用指针的指针。
You need to use pointer to pointer.
//............vv
void bla(char **t)
然后,通过提领它使用指针:
Then use the pointer by dereferencing it:
// note the '*' in front of t
*t = (char*) malloc(5);
if (*t != 0) {
*t[0] = 'h';
printf("%c\n", *t[0]);
}
此外,声明 B
为的char *
,而不是字符B〔10]
。
为什么呢?因为你想改变指针。其中的逻辑是一样的其他类型,但它有点困惑在这里。结果
想想看,是这样的:如果你需要传递一个 INT
,你需要去改变它,你需要一个指针为int 。同样是在这里 - 你需要传递的字符指针并需要哟改变它,所以用指针的字符指针的 :)
Why? Because you're trying to change the pointer. The logic is the same as other types, but it's kinda confusing here.
Think about it like this: if you need to pass an int
and you need to change it, you need a pointer to int. The same is here - you need to pass a pointer to char and you need yo change it, so use "pointer to pointer to char" :)
的 修改的:
根据你的编辑 - 是的,你明白完美这一点,但只是一个小问题 - 运算符*
和优先运算符[]
。如果更换 * T [X]
与(* T)[X]
,everythng将被罚款:)
EDIT:
According to your edit - yes, you have understood this perfectly, there's just a small problem - the priority of operator*
and operator[]
. If you replace your *t[X]
with (*t)[X]
, everythng will be fine :)
这篇关于如何越过一个指针和堆分配空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!