1

I'm trying to write a program that asks from the user to enter couple of names (in this case 3, check out my define), the program, with functions scan_names and print_names would scan the names and print them, no matter what I do I don't succeed with it :(

This is the exception I get: "Exception thrown at 0x0FD6FB7C (ucrtbased.dll) in Magshimim_EX175.exe: 0xC0000005: Access violation reading location 0x00616161."

#include <stdio.h>

#define LINE 3
#define LENGH 10

void print_names(char* names[LENGH], int line)
{
    printf("\nYour names are:\n");
    for (size_t i = 0; i < line; i++) {
        puts(names[i]);
    }
}

void scan_names(char* names[LENGH], int line)
{
    for (int i = 0; i < line; i++) {
        printf("\nEnter name %d:  ", i + 1);
        fgets(names[i],LENGH,stdin);
    }
}

int main(void)
{
    char names[LINE][LENGH] = { NULL };
    scan_names(names, LINE);
    print_names(names, LINE);
}
  • 3
    [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – Swordfish May 09 '19 at 14:57
  • 3
    `gets` has been obsolete for 20 years. Your source of learning is hopelessly outdated and must be replaced. – Lundin May 09 '19 at 15:01
  • It still happened to me when I used in fgets, as well as scanf – shalom shalom May 09 '19 at 15:03
  • Because `gets` is not the problem here. However, learning C from completely outdated sources is a major problem. – Lundin May 09 '19 at 15:04
  • OK, any idea what should I do here in order to solve the problem? – shalom shalom May 09 '19 at 15:07
  • You're passing a 2d array of chars to your functions but they wants a 1d array of pointers to char and your compiler is telling you that. These are "only" warning but they are actually errors. – Jabberwocky May 09 '19 at 15:10

1 Answers1

2

char names[LINE][LENGH] is a 2D array of characters. char* names[LENGH] is a 1D array of character pointers. Like your compiler is telling you if you bother reading the warnings/errors: the types are not compatible.

Change the functions to void print_names(char names[LINE][LENGH], int line).

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • @shalomshalom `names` when used in a function decays into a pointer to the first element. The above is identical to writing `void print_names(char (*names)[LENGH], int line)` but that syntax is just going to look strange and confusing for newbies. – Lundin May 09 '19 at 15:08