1

I am new to C programming, I am trying to run a code snippet that create a dynamic array of struct object and then uses scanf to save values. When I run the code in code blocks it works just fine but throws memory access exceptions in Visual studio 2019

I am attaching code snippet and error trace.

    struct Student
{
    int rollNumber;
    char studentName[10];
    float percentage;
};

int main(void)
{
    int counter;
    struct Student studentRecord[5];

    printf("Enter Records of 5 students");

    for (counter = 0; counter < 5; counter++)
    {
        printf("\nEnter Roll Number:");
        scanf_s("%d", &studentRecord[counter].rollNumber);
        printf("\nEnter Name:");
        scanf_s("%s", &studentRecord[counter].studentName);
        printf("\nEnter percentage:");
        scanf_s("%f", &studentRecord[counter].percentage);

    }

    printf("\nStudent Information List:");

    for (counter = 0; counter < 5; counter++)
    {
        printf("\nRoll Number:%d\t Name:%s\t Percentage :%f\n",
            studentRecord[counter].rollNumber, studentRecord[counter].studentName, studentRecord[counter].percentage);
    }
    return 0;
}

Error:

Exception thrown at 0x7C9AEF8C (ucrtbased.dll) in linkedList.exe: 0xC0000005: Access violation writing location 0x00500000.

4

1 Answer 1

0

You need to specify the size of the buffer (in characters) for the string format specifier, ie %s.

scanf_s( "%9s", studentRecord[ counter ].studentName, 10 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.