Unhandled exception at 0x6BE20E11 (ucrtbased.dll) in labs.exe: 0xC0000005: Access violation reading location 0x0000004D

1

It looks like there are bugs in my function makeUpper. I have tried pointer and some other ways, but it didn't work. And here are what in the sorting.txt :

Michigan

Montana

New York
Alabama

WYOMING

South Carolina

mISSISSIPPI

Iowa

ohio

My aim is to make all the letters in upper cases and listing them in alphabetic order. Please help me.

#include <stdio.h>
#include <string.h>
#include <ctype.h>
void bubblesort(char line[][30], int n);
void swapStrings(char *first[], char *second[]);
void makeUpper(char first[][30], char upperFirst[][30]);

int main()
{
    char state[NUM][30];
    char upper[NUM][30];
    int i, nspot;
    FILE* infile;

    /*Read file into first array.*/
    infile = fopen("sorting.txt", "r");
    if (infile == 0)
    {
        printf("trouble opening file.\n");
        return(0);
    }

    i = 0;
    while ((fgets(state[i], 30, infile)) != NULL)
    {
        nspot = strlen(state[i]) - 1;
        if (state[i][nspot] == '\n')
            state[i][nspot] = '\0'; 
        i++;
    }

    makeUpper(state, upper);

    bubblesort(upper, NUM);

    for (i = 0; i < NUM; i++)
    {
        printf("%s\n", upper[i]);
    }

    fclose(infile);

    return 0;
}


void bubblesort(char line[][30], int n)
{
    int last;
    int i;

    for (last = n - 1; last >= 1; last--)
        for (i = 0; i <= last - 1; i++)
        {
            if (strcmp(line[i], line[i + 1]) > 0)
            swapStrings(&line[i], &line[i + 1]);
        }
}

void swapStrings(char* first[], char* second[])
{
    char swap[30];

    strcpy(swap, first);
    strcpy(first, second);
    strcpy(second, swap);
}

void makeUpper(char first[][30], char upperFirst[][30])
{
    int i,j;
    int test;

    for (i = 0; i < NUM; i++)
    {
        for (j = 0; j < (strlen(first[i])); j++)
        {
            if (first[i][j] > 90)
                strcpy(upperFirst[i][j], toupper(first[i][j]));
            else
                strcpy(upperFirst[i][j], first[i][j]);
        }
        upperFirst[i][strlen(first[i])] = '\0';
    }
}
c++
asked on Stack Overflow Apr 16, 2017 by ShunZ • edited Apr 16, 2017 by zhm

1 Answer

0

Instead of this:

strcpy(upperFirst[i][j], toupper(first[i][j]));

you need this:

upperFirst[i][j] = toupper(first[i][j]);

answered on Stack Overflow Apr 16, 2017 by Mike Nakis

User contributions licensed under CC BY-SA 3.0