c - 我的函数调用有什么问题?

标签 c

<分区>

我在函数调用点遇到段错误。请帮忙提供任何信息。我是编码的新手,所以非常感谢您提供任何帮助!段错误发生在“主要”功能中。

#include<stdio.h>
#include<stdlib.h>
#define MAX 100

void write();
void read();

int main()
{
    int x;

    while(x!=2)
    {
        printf("Type 0 to go to write program, type 1 to go to read program, type 2 to end program\n");
        scanf("%d",x);
        if(x==0)
            write();
        if(x==1)
            read();
    }
    return 0;
}

void write()
{
    FILE *finalptr;
    char name[MAX],gift[MAX];
    int none;

    if((finalptr=fopen("names.dat","w"))==NULL)
    {
        printf("File could not be opened\n");
    }

    else
    {
        printf("Enter the gifter's name2gift.\n");
        printf("Enter EOF to end input.\n");
        printf("? ");
        scanf("%s%d%s",name,none,gift);

        while(!feof(stdin))
        {
            fprintf(finalptr,"%s %s\n",name,gift);
            printf("? ");
            scanf("%s%d%s",name,none,gift);
        }
        fclose(finalptr);
    }
}

最佳答案

scanf("%d",&x);

读取到变量的地址。 &x 不是 x。 由于您将 %d 作为 scanf() 的第一个论点,因此第二个参数应该是某个有效的内存位置(int *),应该将值读取到该位置并放入您的情况是因为 x 未初始化或 x 未指向任何有效的内存位置,这将导致段错误。

修复所有的scanf()

PS: Using uninitialized values will lead to UB( The value x is not initialized and it is being used )

关于c - 我的函数调用有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27646603/

相关文章:

c++ - free如何处理空指针

C 通过引用函数传递复杂结构

c - 从一个大数组中填充一个数组,一次填充两个元素

c - Darwin 真的没有mremap吗?

c - C中的文件处理;不会接受输入

c - 如何用我定义的错误消息替换 Linux 内核错误消息?

c - 如何删除 C 中字符串的子字符串

c - 我们不能用指针进行什么操作?

c - Lua函数的返回值

c - 从多个进程调用系统调用