【发布时间】:2021-04-21 23:36:12
【问题描述】:
我有一个变量 str,它是“Hello Me”。
我想写一个程序,只显示字符串的前 5 个字符,即 Hello。
下面是我尝试执行此操作的代码的 sn-p。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <malloc.h>
#include <string.h>
int main(int argC, char **argV)
{
char str[100]="Hello Me";
char c[100];
sprintf(c,"%s\n",str[1,4]);
printf("string is %s\n",str);
}
不幸的是,在尝试执行此操作时,我遇到了分段错误错误。如何调整程序以获得所需的结果。我需要将 c 之类的字符显示为数组。
【问题讨论】:
-
str[1,4]和str[4]一样,都是单个字符,不是字符串。这就是段错误的原因。要修复它,请尝试sprintf(c, "%.5s\n", str);。当然,您必须在 printf 中打印c才能看到结果。 -
现在,如果我想以第二个字符开始字符串,例如 c 等于 ello,我该怎么办?
-
提示:
char* str = "..."。除非您需要 mutable 缓冲区,否则不要打扰[100]。你可以让它像char str[] = "..."一样自动调整大小。 -
这能回答你的问题吗? Strings in C, how to get subString