Exception thrown at 0x6D4DE559 (ucrtbased.dll) in firstapp1.exe: 0xC0000005: Access violation writing location 0x00000000

1

I have looked this up online and I could only find threads for C++, while i'm using C, so I come and ask, sorry if duplicate.

I'm still learning and I'm trying to understand

I just learned about strcpy and strcmp, but my brain simply can't process why the following code won't work;

void ifelse();
char nametype[100]; 
char typeofname[100];
char truth[100];

int main() {

    char name[100];
    int age;


    printf("\n Print \n");
    ifelse();
    printf("Enter your name: ");
    fgets(name, 100, stdin);
    printf("Enter your age: ");
    scanf("%d", &age);
    if (age > 50) {
        strcpy(truth[100], "and you are an old person.");
    }
    if (age < 50) {
        strcpy(truth[100], "and you are relatively young.");
    }
    else {
        strcpy(truth[100], "and you're a middle age person with issues...");
    } 

    printf("Hello, your %s is %s, %s", nametype, name, truth);

    return 0;
}

void ifelse() {

    printf("Enter your name type (firstname/lastname): ");
    fgets(typeofname, 100, stdin);
    if (strcmp(typeofname, "firstname") == 0) {
        strcpy(nametype[100], "first name");
    }
    if (strcmp(typeofname, "lastname") == 0) {
        strcpy(nametype[100], "last name");
    }
}

within the if if and else statements I get an error while trying to copy the string called "truth", I also tried typing strncpy just in case, but nope.

it's supposed to continue to the print function at the bottom but either it won't print the variables or it's gonna output an allocation error

c
memory
asked on Stack Overflow Jan 13, 2019 by YaRmgl • edited Jan 13, 2019 by YaRmgl

1 Answer

0

strcpy accepts two pointers to buffers, or in other words - arrays. truth[100] is not a pointer to a buffer, it is an element just after the array. So proper calls should be like below:

strcpy(truth, "and you are an old person.");
strcpy(nametype, "first name");

Make correct all similar calls in your code.

answered on Stack Overflow Jan 13, 2019 by S.M. • edited Jan 13, 2019 by S.M.

User contributions licensed under CC BY-SA 3.0