Passing a char pointer to C

Ok, so I'm trying to pass a char pointer to another function. I can do this with a char array, but not with a char pointer. The problem is that I do not know its size, so I can not declare anything about the size inside the main() function.

 #include <stdio.h> void ptrch ( char * point) { point = "asd"; } int main() { char * point; ptrch(point); printf("%s\n", point); return 0; } 

However, this does not work; these two work:

1)

 #include <stdio.h> int main() { char * point; point = "asd"; printf("%s\n", 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\n", point); return 0; } 

So, I'm trying to understand the cause and possible solution to my problem.

+4
source share
5 answers
 void ptrch ( char * point) { point = "asd"; } 

Your pointer is passed in a value , and this code copies and then overwrites the copy . Thus, the original pointer is not touched.

PS It should be noted that when you do point = "blah" , you create a string literal, and any attempt to change is Undefined behavior , so it must be really const char *

Fix - pass the pointer to the pointer , as @Hassan TM does, or return the pointer as shown below.

 const char *ptrch () { return "asd"; } ... const char* point = ptrch(); 
+5
source

This should work as a pointer to a char pointer is passed. Therefore, any changes to the pointer will be visible outside of this.

 void ptrch ( char ** point) { *point = "asd"; } int main() { char * point; ptrch(&point); printf("%s\n", point); return 0; } 
+11
source

Here:

int main() { char * point; ptrch(point);

You pass point by value. ptrch then sets its local copy of point to point to "asd" , leaving point in main untouched.

The solution is to pass a pointer to the main point :

void ptrch(char **pp) { *pp = "asd"; return; }

+2
source

If you change the value of a pointer in a function, it will remain changed only in this function call. Do not confuse your head with pointers and try:

 void func(int i){ i=5; } int main(){ int i=0; func(i); printf("%d\n",i); return 0; } 

Same thing with your pointer. You do not change the address to which it points.

If you assign a variable passed by value, the variable outside the function will remain unchanged. You can pass it with a pointer ( to a pointer ) and change it, replacing it, and it will be the same with int - in this case, it does not matter whether the type is int or char *.

+1
source

first declare funtion ...... like this

  #include<stdio.h> void function_call(char s) 

write the main code next .....

 void main() { void (*pnt)(char); // pointer function declaration.... pnt=&function_call; // assign address of function (*pnt)('b'); // call funtion.... } 
0
source

All Articles