-
char * return
i m srry can anyone post a code where it return char * coz i dont understand char * returns
thanks alot me tried this but didnt work.
Code:
#include <stdio.h>
char *buffer functionizer()
{
scanf("%s",buffer);
return buffer;
}
int main(void)
{
char buffer[100];
buffer=functionizer();
puts(buffer);
return getchar();
}
-
There's nothing wrong with the return buffer; statement. But you do not have char * buffer in the scope of your function "functionizer() " You could deliver the buffer in functionizer() as an argument, or allocate it in that function (but not as local variable!).
If you delivered the buffer in functionizer() as argument (which is better idea in my opinion), it will became
Code:
char *functionizer(char *buffer)
{
.
.
.
}
Note that you should not give name to values returned from a function. Eg.
Code:
//No name for returned int
int sum(int first, int second)
{
return first+second;
}
//no name for returned char pointer.
char *funcniz(char *buffer, size_t buffsize)
{
memset(buffer,o,buffsize);
return buffer;
}
However, since in this example I pass pointer to buffer in function (Eg, location in memory where the buffer starts), I do not need to return the buffer (which once again is the location). Location has not changed, even though the contents of this location did change. In other words, modifications the function did to contents of buffer, will be visible in calling function whether we return the pointer or not.
-
Me tried this but still not work
Code:
#include <stdio.h>
char *functionlizer()
{
char *buffer="HELLO";
return buffer;
}
int main(void)
{
char buffer[100];
buffer=functionlizer();
puts(buffer);
return getchar();
}
-
in main replace char buffer[100] with char *buffer. You reserve the space for actual string in functionalizer. In functionalizer you use now string literal, which is not same as char array. Besides youre in danger returning a pointer to data which is not present in calling function.
-
yah I understand now thanks
-
I don’t really appreciate using this paradigm to return a value from main. IF the getchar fails you’re returning EOF which is not your main objective. Better to type in return 0.
-ssharish
-
Better have a look at
SourceForge.net: Common mistakes and errors - cpwiki
Especially string literals and using pointers without allocating them.