-4

getting runtime error SIGTSTP on codechef, can't find whats wrong, when i compile and this code on my system it work upto for loop after that it stuck. this is my code

#include <stdio.h>
struct invent
{
    char *name[20];
    int number;
    float price;
};
int main()
{
    struct invent product[3], *ptr;
    printf("input\n\n");
    for(ptr = product; ptr < product+3; ptr++)
        scanf("%s %d %f", ptr->name, &ptr->number, &ptr->price);
    printf("\nOutput\n\n");
    
    for(ptr = product;ptr < product + 3; ptr++)
    {
        printf("%-20s %5d %10.2f\n", ptr->name, ptr->number, ptr->price);
    }
    return(0);
}
Ðаn
  • 10,934
  • 11
  • 59
  • 95
  • 2
    [Compile with warnings enabled](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings) and the compiler will tell you what the problem is. – Sneftel Aug 16 '21 at 15:07
  • You probably want `char name[20];`. – Retired Ninja Aug 16 '21 at 15:13
  • I think you should declare your stuct as struct invent { char name[20]; int number; float price; }; – AdabH Aug 16 '21 at 15:14

1 Answers1

0

You should init the struct before you filled it , and use a table of char instead of table of pointer of char

#include <stdio.h>
#include <string.h>
struct invent
{
    char name[20];
    int number;
    float price;
};
int main()
{
    struct invent product[3], *ptr;
    printf("input\n\n");
    for(ptr = product; ptr < product+3; ptr++) {
        memset(ptr, 0 , sizeof(*ptr));
        scanf("%s %d %f", ptr->name, &ptr->number, &ptr->price);
    printf("\nOutput\n\n");
    }
    
    for(ptr = product;ptr < product + 3; ptr++)
    {
        printf("%20s %5d %10.2f\n", ptr->name, ptr->number, ptr->price);
    }
    return(0);
}
AdabH
  • 152
  • 13
  • A strong answer would explain why. – user4581301 Aug 16 '21 at 15:31
  • i tried it, but it give the same error – Avinash Kumar Gupta Aug 16 '21 at 15:50
  • Are you sure it is exactly the same error? You could get similar problems if the name given by the online judge exceeds the 19 character limit you've specified (19 characters plus null terminator = 20). Regardless, the above does fix a crippling bug, and nothing prevents you from having TWO bugs. – user4581301 Aug 16 '21 at 16:01
  • i updated my response , and i tested it without having error – AdabH Aug 16 '21 at 16:03
  • 1
    Assuming the given inputs are valid, the just-added `memset` will change nothing. It would be better to check `scanf`'s return value and make sure it didn't fail. Note that it cannot detect a buffer overrun if the input string is too long.. – user4581301 Aug 16 '21 at 16:03