Re: Iterating trough a int **array. ANSI-C?

Discussion in 'C Programming' started by Joe Wright, Aug 18, 2003.

  1. Joe Wright

    Joe Wright Guest

    Tor Hildrum wrote:
    >
    > Imagine I have:
    > int **array;
    >
    > array = malloc(n * sizeof(int *);
    >
    > for(i=0;i>n:++i)
    > {
    > array = malloc(n * sizeof(int));
    > }
    >
    > Then fill it with values.
    >
    > Then I want a function that takes the address of the first
    > element and number of elements to print out all elements.
    >
    > void print2darray(int *array, int n)
    > {
    > int i;
    >
    > for(i = 0; i < n; ++i)
    > {
    > printf("%d ", *array++); /* or array */
    > }
    > printf("\n");
    > }
    >
    > I'm guessing the behaviour isn't defined?
    > Is there a better/correct way to do this?
    >
    > Tor


    #include <stdio.h>
    #include <stdlib.h>

    void print2d(int *arr, int m) {
    while (m--)
    printf("%d", *arr++);
    printf("\n");
    }

    int main(void) {
    int i, j, n = 10;
    int **array;
    array = malloc(n * sizeof *array);
    for (i = 0; i < n; ++i)
    array = malloc(n * sizeof *array);
    for (i = 0; i < n; ++i)
    for (j = 0; j < n; ++j)
    array[j] = i + j;
    print2d(*array, n);
    return 0;
    }

    --
    Joe Wright mailto:
    "Everything should be made as simple as possible, but not simpler."
    --- Albert Einstein ---
    Joe Wright, Aug 18, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Sandra Castellanos

    Iterating trough controls

    Sandra Castellanos, Apr 30, 2004, in forum: ASP .Net
    Replies:
    3
    Views:
    316
    Teemu Keiski
    May 1, 2004
  2. Schnoffos
    Replies:
    2
    Views:
    1,196
    Martien Verbruggen
    Jun 27, 2003
  3. Matt Gregory

    Re: Iterating trough a int **array. ANSI-C?

    Matt Gregory, Aug 18, 2003, in forum: C Programming
    Replies:
    5
    Views:
    735
    Kevin Easton
    Aug 18, 2003
  4. Hal Styli
    Replies:
    14
    Views:
    1,613
    Old Wolf
    Jan 20, 2004
  5. Kevin Börgens

    Iterating trough hash

    Kevin Börgens, Nov 9, 2004, in forum: Ruby
    Replies:
    18
    Views:
    205
    Gavin Kistner
    Nov 10, 2004
Loading...

Share This Page