当我尝试使用printf(" %s",course_comment(1.0) );
调用我的函数时,程序会崩溃。这是我的函数:
char *course_comment(float b)
{
if(b < 2.0)
return("Retake");
}
为什么它会崩溃?我该如何修复它?
如果您的字符串是常量且没有意图修改结果,则使用字符串字面值是最好的选择,例如:
```#include <stdio.h>
static const char RETAKE_STR[] = "Retake";
static const char DONT_RETAKE_STR[] = "Don't retake";
const char *
course_comment (float b)
{
return b < 2.0 ? RETAKE_STR : DONT_RETAKE_STR;
}
int main()
{
printf ("%s or... %s?\n",
course_comment (1.0),
course_comment (3.0));
return 0;
}
strdup
克隆字符串 (不要忘记使用 free
释放它):#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *
course_comment (float b)
{
char result[256];
if (b < 2.0)
{
snprintf (result, sizeof (result), "Retake %f", b);
}
else
{
snprintf (result, sizeof (result), "Do not retake %f", b);
}
return strdup (result);
}
int main()
{
char *comment;
comment = course_comment (1.0);
printf ("Result: %s\n", comment);
free (comment); // Don't forget to free the memory!
comment = course_comment (3.0);
printf ("Result: %s\n", comment);
free (comment); // Don't forget to free the memory!
return 0;
}
#include <stdio.h>
const char *course_comment(float b); // <- fn prototype
int main(int argc, char *argv[]) {
printf(" %s",course_comment(1.0f));
}
const char *course_comment(float b)
{
if(b < 2.0)
return("Retake");
}
建议返回一个const char *的文字,因为它们无法被修改。
如果b不小于2.0,您的函数会返回什么? 如果您尝试使用返回值会发生什么? 是您的确切代码导致了崩溃吗?
1.0
,所以这不是问题。 - Michael Mrozek返回这样的指针并不是特别美观的。你能做的最好的事情就是像这样:
main.c
#include "some_other_file.h"
int main()
{
printf(" %s", course_comment(1.0f) );
return 0;
}
some_other_file.h
#ifndef YADA_YADA_H
#define YADA_YADA_H
const char* course_comment(float b);
#endif
some_other_file.c
static const char COMMENT_RETAKE [] = "Retake";
const char* course_comment(float b)
{
const char* result;
if(b < 2.0f)
{
result = COMMENT_RETAKE;
}
else
{
result = ""; /* empty string */
}
return result;
}
因为1.0不返回任何内容,所以您得到了一个NULL指针。
不是您的函数崩溃了,而是printf崩溃了:
printf(" %s", NULL);
经验法则:
printf("%s",NULL);
不会崩溃,但会输出(null)
。 - Basile Starynkevitchreturn "blah"
,那么返回类型应该是const char*
。char *
是合法的;只是你不能对其进行写入操作。 - bdonlan
b >= 2.0
,你就没有返回任何东西(这不是你特别的问题,但在某些时候它会成为一个问题)。 - Michael Mrozek