c 中的执行错误:"Segmentation fault (core dumped)"

Execution error in c: "Segmentation fault (core dumped)"

我只是一个C语言的初学者。尝试做一个基本的程序,当我执行并引入任何一个数字时都会出现这个错误。

#include <stdio.h>
int main ()
{
  float a;
  scanf("%f",a);
  printf("%f\n",a);
  return (0);
} 

记住 scanf 是一个函数,你遇到的问题是直接传递变量。通过这样做,程序将收到变量的副本,并且将无法修改包含在 main 中的变量。 Scanf 使用指向数据类型的指针,这就是您需要传递指针的原因。 这应该可以解决它:

scanf("%f",&a);

注意:当使用 & 时,您使用的是该变量的内存位置(与指针相同)。

您遇到段错误的原因是在 scanf 内部,一旦函数接收到用户输入,它将按照

的方式执行某些操作
*a = user_input;//suppose the user_input was a float(already converted from a string) 

如果您直接传递变量,它会尝试推导包含的值。

其实问题出在这里:

scanf("%f",a);

应该是:

scanf("%f",&a);

据人说:

The scanf() family of functions scans input according to format as described below. This format may contain conversion specifications; the results from such conversions, if any, are stored in the locations pointed to by the pointer arguments that follow format. Each pointer argument must be of a type that is appropriate for the value returned by the corresponding conversion specification.

scanf 期望变量 a 地址 ;您实际传递的是变量 acontents,即 a) indeterminate1,并且 b) 很可能不是有效的 2 地址。

您需要使用一元运算符&来获取a地址:

scanf( "%f", &a );

此规则的例外是当您读取字符串并将其存储到 char 数组时;数组是特殊的,在大多数情况下,数组表达式被视为 就好像 它是指向数组第一个元素的指针,所以当读取文本字符串时,你会做类似以下:

char str[N]; // for some size N
scanf ("%s", str ); // no & for array parameters


1。除非它是在文件范围内(在任何函数体之外)或使用 static 关键字声明的,否则变量不会被初始化为任何特定值;它的内容将是随机垃圾。
2. 在这种情况下,"valid" 表示程序中变量的地址。