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);
}
6
  • 3
    Why is the gets function so dangerous that it should not be used? Commented May 9, 2019 at 14:57
  • 3
    gets has been obsolete for 20 years. Your source of learning is hopelessly outdated and must be replaced. Commented May 9, 2019 at 15:01
  • It still happened to me when I used in fgets, as well as scanf Commented May 9, 2019 at 15:03
  • Because gets is not the problem here. However, learning C from completely outdated sources is a major problem. Commented May 9, 2019 at 15:04
  • OK, any idea what should I do here in order to solve the problem? Commented May 9, 2019 at 15:07

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

@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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.