Search code examples
cfgets

fgets "Access violation writing location 0xCCCCCCCC." error


Error: Unhandled exception at 0x60092A8D (msvcr110d.dll) in C_Son60.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC.

When below code executed this error code is given.(Compiles successfully) Where is my mistake?

#include <stdio.h>

int i;

int main(void){

char *names[3];

//get the names of the cities
puts("Enter names of cities");
for (i = 0; i < 3; i++)
{
    fgets( names[i], 99, stdin);
}
//print entered names
for (i = 0; i < 3; i++)
{
    printf("%s", *names[i]);
}

getch();
}

Solution

  • 2 things:

    1. you need to allocate the strings you created- you can do it with malloc(100 * sizeof(char))
    2. when printing you do *names[i] which means - **(names + i).

    all you need is names[i]

    use the code:

    #include <stdio.h>
    
    int i;
    
    int main(void){
        char *names[3];
    
        //get the names of the cities
        puts("Enter names of cities");
        for (i = 0; i < 3; i++)
        {
            names[i] = (char *)malloc(100 * sizeof(char));
            fgets( names[i], 99, stdin);
        }
        //print entered names
        for (i = 0; i < 3; i++)
        {
            printf("%s", names[i]);
        }
    
        getch();
    }