2
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();
}
karthika
  • 4,085
  • 3
  • 21
  • 23
Lyrk
  • 1,936
  • 4
  • 26
  • 48

3 Answers3

4

You need to allocate memory to which the char pointers point to before you read them in

for instance:

for (i = 0; i < 3; i++)
{
  names[i] = malloc(200);
  fgets( names[i], 99, stdin);
}
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
2

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();
}
No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
1

You must allocate your memory before storing anything into it. When you need to allocate an array of elements, and you do not know the number of elements at compile time, you must use malloc() to allocate them.

Don't forget to free your dynamically allocated memory later in order to avoid memory leaks!

Natan Streppel
  • 5,759
  • 6
  • 35
  • 43