我编写这段代码是为了接受一个字符串,直到它应该提取一个字符串并将其打印出来。 以下是代码:
#include <stdio.h>
#include <stdlib.h>
int strlen(char s[]){
int i = 0;
while(s[i]!='\0')
i++;
return i;
}
char *extract(char s[], int n){
char *result = (char *)malloc(sizeof(char)*3);
for(int j=0;j<n;j++){
result[j]=s[j];
}
return result;
}
int main(){
char str[100];
int till;
printf("Enter a string: ");
scanf("%s", str);
printf("Until where to extract: ");
scanf("%d", till);
char *ret = extract(str, till);
printf("%s is extracted", ret);
return 0;
}
是这样的:
Enter a string: hello
Enter from where to extract: 2
然后它崩溃了。 我不明白问题是什么。
最佳答案
首先,你需要改变
scanf("%d", till);
到
scanf("%d", &till);
作为scanf()
需要一个指向所提供格式说明符的数据类型参数的指针。使用错误类型的参数会导致 undefined behavior .
然后,还有很多问题,比如
- 您只分配了 3 个
char
,您在其中根据n
的传入值进行循环。 - 您从未检查过
malloc()
是否成功。 - 您没有以 null 终止您打算稍后用作字符串的
结果
。
也就是说,
您应该始终限制字符串的输入以避免超限的可能性,例如
scanf("%99s", str); //considering the length of the array is 100.
有一个库函数
strlen()
可用于string.h
。即使您想推出自己的功能,也请尝试遵循不同的命名约定。您没有
free()
分配的内存。
关于提取字符串崩溃的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32891356/