甚至可能吗?假设我想返回一个包含两个字符的数组
char arr[2];
arr[0] = 'c';
arr[1] = 'a';
Run Code Online (Sandbox Code Playgroud)
从一个功能.我甚至用什么类型的功能?我唯一的选择是使用指针并使函数无效吗?到目前为止,我已经尝试过char*函数或char [].显然你只能有char(*[])的功能.我想避免使用指针的唯一原因是函数必须在遇到"返回内容"时结束.因为"something"的值是一个字符数组(不是字符串!),它可能会根据我通过main函数传递给函数的值来改变大小.感谢任何提前回复的人.
我正在编写一个从标准输入返回一个字符串的程序,但我收到警告,它返回一个本地 wariable 的地址。我怎样才能返回字符串?
提前致谢
#include <stdio.h>
char* readLine()
{
int i;
char input[1024];
for(i=0;i<1024;i++)
{
input[i]=fgetc(stdin);
if(input[i]=='\n')
{
break;
}
}
return input;
}
int main()
{
printf("%s",readLine());
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我有以下代码:
#include <stdio.h>
char * lookLine (FILE *fichero)
{
char p[25];
fgets (p, sizeof (p), fichero);
return p;
}
int main (void) {
printf ("%s\n", lookLine (fopen ("suma.c", "r")));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
#??x?
Run Code Online (Sandbox Code Playgroud)
不太好.我打算打印出名为"suma.c"的文件的第一行.它应该打印出以下内容:
#include <stdio.h>
Run Code Online (Sandbox Code Playgroud)
不过,如果我将p字符串的内容打印到同一个lookFile函数中,它就可以了:
#include <stdio.h>
void lookLine (FILE * fichero)
{
char p[25];
fgets (p, sizeof (p), fichero);
printf ("%s\n", p);
}
int main (void) {
lookLine (fopen ("suma.c", "r"));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我现在得到的输出是正确的:
#include <stdio.h>
Run Code Online (Sandbox Code Playgroud)
我的理由是:通过使用fgets我保存p数组中第一行"name.c"的字符串,然后返回其地址,该地址由 …