I'm trying to recall a bit about C programming.
And one task I found for myself - is to pass string's variable between functions with pointers.
So - what I want to do:
- create an array;
- create a pointer to this array;
- pass pointer as an argument to another function;
- call
getcwd()
inside second function; - print result.
And here is my code:
#include <stdio.h>
#include <unistd.h>
int ch_str(char point1[]) {
printf("Point 1: %s\n", point1);
}
int getpath (char point2[]) {
printf("Path: %s\n", getcwd(point2, sizeof(point2)));
}
int main () {
char str[20] = "this is string";
char *pStr;
pStr = &str;
ch_str(pStr);
char pathname[1024];
char *pPathname;
pPathname = &pathname;
getpath(pPathname);
printf("Direct: %s\n", getcwd(pathname, sizeof(pathname)));
return 0;
}
ch_str()
here - is just "test" for me, to be sure I'm doing right (he-he) with pointers. And - this part works.
But getcwd()
with pointer as an argument - just retun "null":
$ ./deploy Point 1: this is string Path: (null) Direct: /home/setevoy/ci
I suppose - here is some (big...) misunderstanding of the pointers in C from my side, but:
The
getcwd()
function copies an absolute pathname of the current working directory to the array pointed to by buf
Array (pathname[1024]
) passed with the pointer pPathname
, so - why getcwd()
can't save path to pathname[1024]
location? What I can't see here?