尝试在指针内写入数据时出现分段错误异常

问题描述 投票:0回答:1

我遇到了一个例外:第 54 行出现分段错误,我在其中输入了品牌名称。 C语言。我正在使用带有 C/C++ Compile Run 扩展的 VScode。

    do
    {
        printf("Enter brand: ");
        scanf("%s", *tab[i].brand);

        if (!isalpha(*tab[i].brand))
        {
            printf("Brand must consist of letters!\n");
        }
    } while (!isalpha(*tab[i].brand));

输入品牌名称时,它会将错误指向 stdio.h 文件第 291 行:“__retval = __mingw_vfscanf( stdin, __format, __local_argv );”。 我试图将数据放入结构内部的指针中。尽管我不确定我做得对,但 chatgpt 给了我类似的答案,但不能解决问题。有人可以指出我做错了什么吗,指针对我来说很难理解。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

struct Car
{
    double price;
    char *brand;
};


void createAndPrint(int n, struct Car *tab)
{
    for (int i = 0; i < n; i++)
    {
        tab[i].brand = malloc(sizeof(char) * 100);
        
        printf("\nENTER DETAILS FOR CAR NO %d\n", i + 1);
        
        do
        {
            printf("Enter price: ");
            scanf("%lf", &tab[i].price);
            
            if (tab[i].price < 0)
            {
                printf("Price cannot be < 0!\n");
            }
        } while (tab[i].price < 0);

         do
        {
            printf("Enter brand: ");
            scanf("%s", *tab[i].brand);

            if (!isalpha(*tab[i].brand))
            {
                printf("Brand must consist of letters!\n");
            }
        } while (!isalpha(*tab[i].brand)); 
        

        free(tab[i].brand);
    }
        for (int i = 0; i < n; i++)
        {
            printf("\nCAR INFORMATION NO %d\n", i + 1);
            printf("Price: %.2lf\n", tab[i].price);
            printf("Brand: %s\n", *tab[i].brand);
        }
}

int main()
{
    int n;
    printf("Enter the number of cars: ");
    scanf("%d", &n);

    struct Car *tab = malloc(n * sizeof(struct Car));

    createAndPrint(n, tab);

    free(tab);
}
c pointers struct segmentation-fault
1个回答
0
投票

这部分代码

 do
{
    printf("Enter brand: ");
    scanf("%s", *tab[i].brand);

    if (!isalpha(*tab[i].brand))
    {
        printf("Brand must consist of letters!\n");
    }
} while (!isalpha(*tab[i].brand)); 

    

free(tab[i].brand);

没有意义。

如果您想输入单个字符,则不要调用 scanf

scanf("%s", *tab[i].brand);

你需要写

scanf(" %c", *tab[i].brand);

如果你想输入一个字符串那么你需要写

scanf("%100s", tab[i].brand);

在最后一种情况下这条消息

printf("Brand must consist of letters!\n");

也没有什么意义,因为只检查输入字符串的第一个字符。

这个免费的电话

free(tab[i].brand);

立即释放分配的数组。

结果是这个for循环

for (int i = 0; i < n; i++)
{
    printf("\nCAR INFORMATION NO %d\n", i + 1);
    printf("Price: %.2lf\n", tab[i].price);
    printf("Brand: %s\n", *tab[i].brand);
}

调用未定义的行为,因为它尝试访问已释放的字符数组

brand

© www.soinside.com 2019 - 2024. All rights reserved.