This has no output. Help.Code:#include <stdio.h> int main(void) { // you need malloc otherwise memory error. char* string=(char*)malloc(5); set(string); printf("%s",string); return 0; } void set(char* s) { s="abc"; }
This has no output. Help.Code:#include <stdio.h> int main(void) { // you need malloc otherwise memory error. char* string=(char*)malloc(5); set(string); printf("%s",string); return 0; } void set(char* s) { s="abc"; }
This works.
Code:#include <stdio.h> int main(void) { // you need malloc otherwise memory error. char* string=(char*)malloc(5); set(string); printf("%s",string); return 0; } void set(char* s) { *s='a'; *(s+1)='b'; *(s+2)='c'; }
In the first code example, you are replacing the value of the local pointer with another value, so of course it doesn't affect the value of the pointer in main, or the value of what that pointer points to. In the second code example, you are modifying what the local pointer points to, and this is the same as what the pointer in the caller points to, hence the changes are reflected in main.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
While it may "work" in the sense of "compile and run without crashing, printing expected output", it isn't correct:Originally Posted by gunitinug
- Before you call a function, it should be declared, either by placing its definition before the definition of the function in which it is called, or by forward declaring it.
- To use malloc, you should #include <stdlib.h>
- Whenever you use malloc, you should have a corresponding call to free.
- You don't need malloc at all: you are going to overwrite the pointer with a pointer to the first character of "abc", so you don't need to allocate any additional space for the pointer to point to.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Please do not use cast for malloc function.
And further to laserlight's comment, if you did call free, it would most likely crash.
You were on the right track in post #2, where this is simpler.Code:char* string=malloc(5); set(&string); printf("%s",string); free(string); //!! oops, string no longer points to what malloc returned return 0;
Code:void set(char* s) { strcpy(s,"abc"); }
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.