![]() |
| | #1 |
| Registered User Join Date: May 2009
Posts: 5
| 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. Code: /*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));
}
printf("\n");
}
main(){
double arr[5] = { 2.5, 3.2, 18.7, -1.35, 4.2 };
matrix_print(1, 5, *arr[5]); //causing an error
}
Thanks in advance! |
| zeebo17 is offline | |
| | #2 |
| Banned Join Date: Mar 2009
Posts: 533
| your function expects a pointer to a double you are passing in a double (located outside the bounds of arr)
__________________ ╔╗╔══╦╗ ║║║╔╗║║ ║╚╣╚╝║╚╗ ╚═╩══╩═╝ |
| ಠ_ಠ is offline | |
| | #3 |
| Registered User Join Date: Apr 2009 Location: Russia
Posts: 116
| Code: matrix_print(1, 5, arr); Code: for (i = 0; i < col; i++)
printf("%g ",*(m+row*i));
putchar('\n');
|
| c.user is offline | |
| | #4 |
| Registered User Join Date: Sep 2007
Posts: 372
| 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: Code: #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));
}
putchar('\n');
}
int main(void)
{
double a[5] = { 2.5, 3.2, 18.7, -1.35, 4.2 };
f(a, 5);
return 0;
}
Code: void f(double a[]); Code: void f(double *a); |
| cas is offline | |
![]() |
| Tags |
| arrays, pointers |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Dynamic array of structures containing yet another dynamic array of structures | innqubus | C Programming | 2 | 07-11-2008 07:39 AM |
| using realloc for a dynamically growing array | broli86 | C Programming | 10 | 06-27-2008 05:37 AM |
| Syntax for constant array of array pointers | BMintern | C Programming | 4 | 05-14-2008 08:21 AM |
| Is there a way to find the number of elements in an array? | lime | C Programming | 2 | 08-03-2003 10:01 AM |
| how to create a linked list of items using pointers stored in a two dimensional array | Unregistered | C Programming | 5 | 11-20-2001 12:48 PM |