I am getting an exception: Segmentation fault on the line 54, where I put in a brand name. C language. I am using VScode with C/C++ Compile Run extension.
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));
When putting in an brand name it points the error to stdio.h file on line 291: " __retval = __mingw_vfscanf( stdin, __format, __local_argv );". I am trying to put data inside an pointer that is inside an struct. Although I am not sure I do it right, chatgpt gives me similar answers that do not resolve the issue. Can some point out what am I doing wrong, pointers are hard for me to understand.
#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);
}
This part of your code
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);
does not make sense.
If you want to enter a single character then instead of this call of scanf
scanf("%s", *tab[i].brand);
you need to write
scanf(" %c", *tab[i].brand);
If you want to enter a string then you need to write
scanf("%99s", tab[i].brand);
and in the last case this message
printf("Brand must consist of letters!\n");
also does not make sense because only the first character of the entered string is checked.
This call of free
free(tab[i].brand);
at once frees the allocated array.
As a result this for loop
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);
}
invokes undefined behavior because it tries to access the already freed character array brand
.