【发布时间】:2021-01-31 22:57:51
【问题描述】:
我不确定为什么在我尝试查看 teacher.first 正在打印的索引时会出现段错误。 我使用 strcpy 将字符串 Adam 放置在一个 char 类型的数组中,即在一个结构中。但是我不确定为什么当我尝试查看索引 0 处的内容时它会给我一个段错误。
我的假设:
- 当我们没有分配足够的内存时会产生段错误。 -strcpy(老师。第一,“亚当”);当在程序开始时声明时,将字符串 Adam 放在给定 32 字节内存的 char/string 数组的索引 0 处。 可能性:
- strcpy(teacher.first, "Adam");将字符串 Adam 单独放入数组中,索引 0 不应为“Adam”,而应为 A。
#include <stdio.h>
#include <string.h>
struct person { /* p e r s o n i s name f o r s t r u c t u r e t y p e */
char first[32]; /* f i r s t f i e l d o f s t r u c t u r e i s a r r a y o f
c h a r */
char last[32]; /* s e c o n d f i e l d i s a r r a y o f c h a r */
int year; /* t h i r d f i e l d i s i n t */
double ppg; /* f o u r t h f i e l d i s d o u b l e */
}; /* e n d i n g ; means end o f s t r u c t u r e t y p e d e f i n i t i o n */
void printperson(struct person personinstance) {
printf("Printing struct person properties : \n");
printf("First and last name : %s %s.\n", personinstance.first,
personinstance.last);
printf("Year:%d.\n", personinstance.year);
printf(" Points per game : %lf .\n", personinstance.ppg);
}
int main(int argc, char* argv[]) {
struct person teacher;
int i;
teacher.year = 2005;
teacher.ppg = 10.4;
strcpy(teacher.first, "Adam");
strcpy(teacher.last, "Hoover");
/*Why'd I get a segment fault. You get segment faults when you're trying to
access memory
that doesn't exist. **/
// Segment fault: --> printf("first element of teacher first is: %s\n",
// teacher.first[0]);
// Whats at the first index of the array?
printperson(teacher);
printf("\n");
printf("first element of teacher first is: %s\n", teacher.first[0]);
}
【问题讨论】:
-
编译器不关心格式(大部分),但你的代码很难让人阅读。
-
您的程序看起来正确(如果我们忽略格式)并且在ideone 上的行为与预期一样。你的工具是什么?操作系统?编译器?编译选项?
-
程序在这里编译执行。
-
因为我把它注释掉了。我将编辑代码,使其中断并给出段错误。
-
您的意思是 注释掉代码
printf("first element of teacher first is: %s\n", teacher.first[0]);导致段错误?那是因为teacher.first[0]不是字符串的地址。
标签: c debugging segmentation-fault