Results 1 to 4 of 4

Thread: [C] What is wrong with this code??

  1. #1
    Join Date
    Feb 2007
    Location
    Bucharest
    Beans
    460
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    [C] What is wrong with this code??

    Really basic code. It allocates memory for a nxn two-dimensional array and *tries* to fill it out with zeros:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
    	short unsigned int n, **a, i, j;
    	printf("n: "); scanf("%hu", &n);
    	a = malloc(sizeof(short unsigned int) * n);
    	for (i=0; i < n; i++) {
    		a[i] = malloc(sizeof(short unsigned int) * n);
    		for (j=0; j < n; j++) a[i][j] = 0;
    	}
    	for (i=0; i < n; i++) {
    		for (j=0; j < n; j++) {
    			printf("%hu ", a[i][j]);
    		}
    		puts("");
    	}
    	return 0;
    }
    But it doesn't make it, output:
    Code:
    n: 5
    41136 466 0 0 0 
    0 0 0 0 0 
    0 0 0 0 0 
    0 0 0 0 0 
    0 0 0 0 0
    What is wrong? I can't figure it out for the life of me.
    [ Blog # A Programmer's Ride ]
    Linux: it really whips the penguin's butt.

  2. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Beans
    2,185
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: [C] What is wrong with this code??

    a is a pointer to pointers. This line is wrong:
    Code:
    a = malloc(sizeof(short unsigned int) * n);
    It should have been:
    Code:
    a = malloc(sizeof(short unsigned int *) * n);
    Ubuntu 12.04

  3. #3
    Join Date
    Feb 2007
    Location
    Bucharest
    Beans
    460
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: [C] What is wrong with this code??

    Oh wow, you are right, never thought of that. Thanks a bunch
    [ Blog # A Programmer's Ride ]
    Linux: it really whips the penguin's butt.

  4. #4
    Join Date
    Jan 2008
    Location
    Auckland, New Zealand
    Beans
    3,129
    Distro
    Ubuntu 9.10 Karmic Koala

    Re: [C] What is wrong with this code??

    Usually if you want a 2D array you simply use a 1D array that is n*n long.

    So to access A(i,j) you use A(i*n + j).

    Don't know if that's actually helpful or not but thought I'd point it out.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •