Can't a function return a string without pointers?
I am having a strang开发者_StackOverflowe problem while returning a string. it says can not convert int to const char*
#include<stdio.h>
#include<conio.h>
#include <string.h>
/*The above program shows that you can not return a string from a function normally*/
char check(char str[]);
void main(void)
{
char str[30],str2[30];
printf("Enter a sentence:");
gets(str);
strcpy(str2,check(str));
getch();
}
char check(char str[30])
{
return str;
}
You have to return a char* instead
No, strings are not intrinsic data types in C. See http://c-faq.com/aryptr/index.html
Also, forget that gets()
exists and use fgets()
if you don't want to build bugs into your code. http://c-faq.com/stdio/getsvsfgets.html
The C programming language does not have the data type "string". C supports char arrays and pointers to char.
You can address an array of char by using a pointer though:
char *p;
char str[30];
p = str;
Your function must return a pointer to character. Changing your code to
char* check(char str[30])
{
return str;
}
would work. You must keep in mind that you return the address of the argument that has been passed to function.
If you want to fill any result variable in the function, pass the address to the function:
int check(char* result, char str[]);
void main(void)
{
char str[30], str2[30];
printf("Enter a sentence:");
gets(str);
if (check(str2, str))
{
printf("check succeeded %s\n", str2);
}
getch();
}
int check(char* result, char str[30])
{
int success;
success = ....;
if (success)
{
strcpy(result, str);
}
return v;
}
Are you missing "*" in the return type of check function?
it should be
char*
instead of
char
This compiles:
#include<stdio.h>
#include <string.h>
/*The above program shows that you can not return a string from a function normally*/
char *check(char **str);
int main(void)
{
char str[30],str2[30];
char *p;
p=str;
printf("Enter a sentence:");
fgets(str, sizeof str, stdin);
strcpy(str2,check(&p));
printf("You said: %s\n", str2);
return 0;
}
char *check(char **str)
{
return *str;
}
No, you need to do:
#include<stdio.h>
#include<conio.h>
#include <string.h>
/*The above program shows that you can not return a string from a function normally*/
char check(char str[]);
void main(void)
{
char str[30],str2[30];
printf("Enter a sentence:");
gets(str);
strcpy(str2,check(str));
getch();
}
char *check(char str[30])
{
return str;
}
You could also modify the string within the function without returning it providing you don't try to reallocate its size, for example:
#include<stdio.h>
#include<conio.h>
#include <string.h>
/*The above program shows that you can not return a string from a function normally*/
void check(char *str);
void main(void)
{
char str2[30];
char *str;
str = malloc(30);
printf("Enter a sentence:");
gets(str);
check(str);
strcpy(str2,str);
getch();
}
void check(char *str)
{
strcpy(str, "test");
}
精彩评论