C程序返回的首字母缩写“;分段故障“;
我正在做一个名字缩写的项目,你输入一个名字,然后打印名字缩写。当我尝试组合字符串时,它返回C程序返回的首字母缩写“;分段故障“;,c,strcat,cs50,c-string,C,Strcat,Cs50,C String,我正在做一个名字缩写的项目,你输入一个名字,然后打印名字缩写。当我尝试组合字符串时,它返回Segmentation fault,而不是初始值 #include <stdio.h> #include <stdlib.h> #include <cs50.h> #include <string.h> #include <ctype.h> int main(void) { printf("Name: "); string na
Segmentation fault
,而不是初始值
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void) {
printf("Name: ");
string name = GetString();
printf("\n");
int length = strlen(name);
string initials = "";
int arraylength = length + 1;
char string[arraylength];
string[0] = toupper(name[0]);
int count = 1;
for(int l = 1;l<=length;l++) {
if(name[l] == ' ') {
l++;
count++;
string[l] = toupper(name[l]);
}
}
count++;
string[count] = '\0';
for(int c = 0;c<=count;c++) {
strcat(initials, &string[c]);
}
printf("%s\n", initials);
}
#包括
#包括
#包括
#包括
#包括
内部主(空){
printf(“名称:”);
string name=GetString();
printf(“\n”);
int length=strlen(名称);
字符串首字母=”;
int arraylength=长度+1;
字符字符串[arraylength];
字符串[0]=toupper(名称[0]);
整数计数=1;
对于(int l=1;l,这就是为什么字符串类型会引起混淆,您创建一个指向单个字符的指针,然后将其传递给strcat()
,这完全是错误的
正如strlen()
或strcat()
或所有str
*函数所期望的,字符串不是简单的char
指针,它是代码中的类型string
a中实际上是一个字节序列,最后一个字节是'\0'
,它不是可选的。您创建一个指向单个字符的指针,这与我刚才描述的字符串不同
任何str
*函数都将尝试查找'\0'
,但由于您传递的堆栈变量的地址不是数组,因此当这些函数中的任何函数尝试递增和取消引用传递的指针时,行为都是未定义的
当您了解了字符串在中的工作方式后,您会发现使用strcat()
将一个大字符串的多个块串联在一起不是很有效,您还知道只需要附加一个char
,您可以通过简单地使用索引表示法,如
char string[8];
string[0] = 'E';
string[1] = 'x';
string[2] = 'a';
string[3] = 'm';
string[4] = 'p';
string[5] = 'l';
string[6] = 'e';
string[7] = '\0'; // The very necessary terminator
问:这个“字符串”在你的程序中到底是什么?你能把string
的定义和GetString()
的原型复制到你的帖子中吗?你不能用带有“char”的strcat()
变量。@paulsm4搜索cs50.h我昨天看到它时简直不敢相信。确实cs50.h
因为这种string
类型很糟糕。哈佛不是学习C编程的最佳地方。你添加了什么?你的代码有很多问题。试着先学习字符串,然后再编写代码。