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;
}
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?
EDIT:
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;
}
Output is as follows:
./main
6154128
140488712
97
98
140488712
97
0 <== THIS SHOULD BE 98 AS ABOVE!?
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.
Then use the pointer by dereferencing it:
Also, declare
baschar*, not aschar b[10].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
intand 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” 🙂EDIT:
According to your edit – yes, you have understood this perfectly, there’s just a small problem – the priority of
operator*andoperator[]. If you replace your*t[X]with(*t)[X], everythng will be fine 🙂