Home > Mobile >  Access violation writing location while filling the matrix
Access violation writing location while filling the matrix

Time:10-21

char *inputForMidTask(int &n, char **ptr) {
    printf("Enter the amount of rows: \n");
    scanf("%d", &n);
    for (int i = 0; i < n;   i) {
            gets_s(*(ptr   i), 100); //throws exception here
    }
    return *ptr;
}

void byString() {
    int n;
    char **ptr = (char**)malloc(255 * 255 * sizeof(char));
    *ptr = inputForMidTask(n, m, ptr);
}

Hello! I need to fill in the matrix string by string, but I keep getting an exception error - Exception thrown at 0x78D6FA8D (ucrtbased.dll) in Lab2_Algs.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD. P.S. Memory for **ptr is allocated dynamically by using function malloc

CodePudding user response:

Your byString function allocates one huge buffer but your inputForMidTask function expects n small buffers. It's not clear how to fix it because there is no explanation of what inputForMidTask is supposed to do. Most likely, it should be changed to allocate n small buffers and byString should be changed only to allocate enough space to hold the pointers to the small buffers.

CodePudding user response:

char **ptr means it's an array of pointers. But you allocated an array of 255*255 characters, not pointers.

It should be:

char **ptr = malloc(255 * sizeof(char*));
for (int i = 0; i < 255; i  ) {
    ptr[i] = malloc(255 * sizeof(char));
}

You also never set n before calling inputForMidTask().

And there's not much point in returning *ptr. That's just returning the first line.

  • Related