Thread: Overwriting a row of a dynamic 2D array in C

  1. #1
    Registered User
    Join Date
    Apr 2019

    Overwriting a row of a dynamic 2D array in C

    Hello! I have been trying to come up with a code that overwrites a row of a dynamic 2D array/matrix for quite some time, and when I thought I managed to do it turns out it works for `number of rows>number of columns`type of a matrix only. I am fairly new to this and can not seem to find an error .

    printf("Enter a number of a row you wish to delete: ");
                scanf_s("%d", &k);
                if (k >= 0 && k < vr) { //vr is number or rows
                  for (i = 0; i < kol; i++) { //kol -nmbr of columns
                        unsigned int *tmp;
                        for (j = k + 1; j < vr; j++) a[j - 1][i] = a[j][i];
                        tmp = realloc(a[i], (vr - 1) * sizeof(unsigned int));
                        if (tmp == NULL) {
                        else a[i] = tmp;

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    How is a declared in the first place?

    If you're starting with
    unsigned int **a = malloc( nRows * sizeof(*a));

    Where each row is
    a[i] = malloc( nCols * sizeof(*a[i]));

    To remove a row, it's simply
    for (j = i+1; j < nRows ; j++) a[j-1] = a[j];

    After that, you can use realloc to make a itself shorter, and decrement nRows.

    > //vr is number or rows
    So change the variable to be something actually readable, then you don't need meaningless comments.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. array value overwriting another
    By RyanW2050 in forum C Programming
    Replies: 2
    Last Post: 01-27-2012, 01:34 AM
  2. Bizarre array overwriting
    By LanguidLegend in forum C Programming
    Replies: 2
    Last Post: 11-16-2011, 01:19 PM
  3. Overwriting an integer array
    By bridle17 in forum C Programming
    Replies: 2
    Last Post: 10-02-2011, 11:25 PM
  4. How can I avoid overwriting into an array?
    By Pztar in forum C Programming
    Replies: 3
    Last Post: 06-07-2011, 03:17 PM
  5. Overwriting all in array, why?
    By guesst in forum C Programming
    Replies: 7
    Last Post: 10-09-2008, 05:56 PM

Tags for this Thread