Thread: printing elements of an array using pointers

  1. #1
    Registered User
    Join Date
    May 2009

    printing elements of an array using pointers


    I'm just learning about pointers and as a simple exercise I am trying to print the elements of the array. I'm trying to write a simple function that cycles through the columns and then prints each value to the screen. However, I'm having trouble calling the function properly.

    /*Function the prints a single row array's contents to the screen. */
    void  matrix_print(int row, int col, double *m){
      int i;
      for(i=0; i<col; i++){
        printf("%d  ",*(m+i*col));
      double arr[5] = { 2.5, 3.2, 18.7, -1.35, 4.2 };
      matrix_print(1, 5, *arr[5]);  //causing an error
    The problem in the 3rd argument to the of the matrix_print. The error says that it is an compatible type. Any suggestions?

    Thanks in advance!

  2. #2
    Banned ಠ_ಠ's Avatar
    Join Date
    Mar 2009
    your function expects a pointer to a double
    you are passing in a double (located outside the bounds of arr)

  3. #3
    Registered User
    Join Date
    Apr 2009
        matrix_print(1, 5, arr);
        for (i = 0; i < col; i++)   
            printf("%g  ",*(m+row*i));
    this will print col elements from row (from m)

  4. #4
    Registered User
    Join Date
    Sep 2007
    You're trying to make pointers more complex than they really are. C scales pointer arithmetic, so you don't need to calculate indices. There are two obvious ways to print out your array:
    #include <stdio.h>
    static void f(double *a, int n)
      int i;
      for(i = 0; i < n; i++)
        printf("%f ", a[i]);
        /* or slightly less obvious, imo */
        printf("%f ", *(a + i));
    int main(void)
      double a[5] = { 2.5, 3.2, 18.7, -1.35, 4.2 };
      f(a, 5);
      return 0;
    You can use the array subscript operator (that is, []) on pointers. Arrays and pointers have a close relationship in C, which means that often you can treat them the same way. In fact, the following function declaration:
    void f(double a[]);
    is the same as:
    void f(double *a);
    Don't get the idea that pointers and arrays are the same thing--they're not--but their relationship is such that you can use the array operator on pointers (and, to tell the truth, you can only use it on pointers, but that's another discussion).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. using realloc for a dynamically growing array
    By broli86 in forum C Programming
    Replies: 10
    Last Post: 06-27-2008, 05:37 AM
  3. Syntax for constant array of array pointers
    By BMintern in forum C Programming
    Replies: 4
    Last Post: 05-14-2008, 08:21 AM
  4. Replies: 2
    Last Post: 08-03-2003, 10:01 AM
  5. Replies: 5
    Last Post: 11-20-2001, 11:48 AM

Tags for this Thread

Website Security Test