【问题标题】:Printing off the first element in a array打印出数组中的第一个元素
【发布时间】: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


【解决方案1】:

在 cmets 中,您认为这行代码导致了分段错误:

printf("first element of teacher first is: %s\n", teacher.first[0]);

格式说明符%s 需要一个 c 字符串作为参数,而不是单个字符。要打印单个字符,请使用%c

顺便说一句……

如果您的编译器没有抱怨此问题,请使用更新的编译器来帮助您发现这些错误。例如,clang-7 报告:

main.c:31:53: warning: format specifies type 'char *' but
      the argument has type 'char' [-Wformat]
  ...of teacher first is: %s\n", teacher.first[0]);
                          ~~     ^~~~~~~~~~~~~~~~
                          %c

【讨论】:

  • Welp 修复了它。谢谢
  • 所以基本上当我使用 strcpy(teacher.first, "Adam");那只是一个具有 32 位内存的 1 行数组。当我将 Adam 分配给该内存时,我会用完该内存的 4 个字节。
  • @PlayerUnknown_12 几乎;它是一个由 32 个 字节 内存组成的数组。将 Adam 复制到其中使用 5 个 字节,还有一个用于表示字符串结尾的 \0 字符。
  • 所以现在我想知道为什么 %s 不起作用。我的意思是,“A”不被认为是一个字符串吗?
  • 注意clang报告的错误。 charchar * 不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-24
  • 1970-01-01
  • 2012-09-25
  • 1970-01-01
  • 2019-09-12
  • 1970-01-01
  • 2022-01-13
相关资源
最近更新 更多