linux中我的代码中C的分段错误
我现在只是在学习C语言中的指针,我不知道它们在我的代码中是如何工作的:linux中我的代码中C的分段错误,c,pointers,pass-by-reference,C,Pointers,Pass By Reference,我现在只是在学习C语言中的指针,我不知道它们在我的代码中是如何工作的: #include <stdio.h> #include <string.h> #define MAX_ARR 64 #define MAX_STR 32 typedef enum { COMEDY, DRAMA, HORROR, SCIFI } GenreType; typedef struct { char title
#include <stdio.h>
#include <string.h>
#define MAX_ARR 64
#define MAX_STR 32
typedef enum { COMEDY, DRAMA, HORROR, SCIFI
} GenreType;
typedef struct {
char title[MAX_STR];
char director[MAX_STR];
int year;
GenreType genre;
} MovieType;
void initMovie(char*, char*, int*, GenreType, MovieType*);
void printMovies(MovieType*, int);
void readString(char*);
void readInt(int*);
int main()
{
MovieType movie;
MovieType movieArr[MAX_ARR];
MovieType *pMovie;
char t = movie.title;
int arrSize = 0;
printf("Please enter the tile of the movie: ");
readString(t);
printf("The title of the movie is: %c\n", (t));
return 0;
}
void initMovie(char *t, char *d, int *y, GenreType gentype, MovieType *movType)
{
}
void readString(char *str)
{
char tmpStr[MAX_STR];
fgets(tmpStr, sizeof(tmpStr), stdin);
tmpStr[strlen(tmpStr)-1] = '\0';
strcpy(str, tmpStr);
}
void readInt(int *x)
{
char str[MAX_STR];
readString(str);
sscanf(str, "%d", x);
}
#包括
#包括
#定义最大ARR 64
#定义MAX_STR 32
喜剧、戏剧、恐怖、科幻
}基因型;
类型定义结构{
字符标题[MAX_STR];
char director[MAX_STR];
国际年;
类型体裁;
}电影类型;
void initMovie(char*,char*,int*,GenreType,MovieType*);
无效打印电影(电影类型*,int);
无效读取字符串(字符*);
无效读入(int*);
int main()
{
电影类型电影;
MovieType movieArr[MAX_ARR];
电影类型*pMovie;
chart=movie.title;
int arrSize=0;
printf(“请输入电影的平铺:”);
读取字符串(t);
printf(“电影的标题是:%c\n”,(t));
返回0;
}
void initMovie(char*t、char*d、int*y、GenreType gentype、MovieType*movType)
{
}
void readString(char*str)
{
字符tmpStr[MAX_STR];
fgets(tmpStr、sizeof(tmpStr)、标准DIN);
tmpStr[strlen(tmpStr)-1]='\0';
strcpy(str,tmpStr);
}
void readInt(int*x)
{
字符str[MAX_str];
读字符串(str);
sscanf(str,“%d”,x);
}
我试图要求用户填写电影类型的所有数据,如标题
,导演
,发行年份
等。正如您所看到的,我当前的方法产生了分段错误
,显然我做错了什么。除了initMovie
功能和printMovies
功能(尚未制作)之外,不能更改main
功能之外的所有内容
任何提示和指针,双关语的意图,将不胜感激!让我知道我做错了什么,以及如何修复它 您正在传递
chart=movie.title代码>进入读取字符串(t)代码>。这是不正确的readString
需要一个指针char*
得到它。
所以基本上有两个不同的问题
就像第一个家伙说的,你使用的是chart=movie.title
您应该在何时使用char*t=movie.title代码>
在:printf(“电影的标题是:%c\n”,(t))
您应该使用%s
而不是%c
。就像这样:printf(“电影的标题是:%s\n”,(t))代码>
祝你任务顺利。我使用Mac OS X编译,但它应该可以在linux上运行。语句tmpStr[strlen(tmpStr)-1]='\0'
没有意义,strlen
通过搜索0来计算字符串的长度,然后将0放在已有0的位置。也许你的意思是tmpStr[MAX_STR-1]='\0'
?这不是我做的,但是教授我也不能改变它way@KarstenKoop实际上,它正在剥离fgets()将存储的尾部\n
。所以它确实有道理,尽管它很丑陋。请不要破坏你自己的帖子。chart=movie.title代码>是一个错误。您的编译器应该对此有所说明。在运行程序之前修复编译器报告的所有消息非常重要。+1,然后格式字符串将需要是%s
而不是%c
,并且varargs参数不需要像Python一样放在括号中。