Originally Posted by
Adak
I have not tried what you're doing here, before. It seems to me that if you want to protect the source array, it should be declared constant, instead of just being changed to constant upon arrival in the copy_arr function.
Could you make a constant pointer to array of double, and assign it the base address of the row you're about to have copied, and send that pointer, instead?
Sasha, I have one thing to ask of you. Please shorten any line length inside your code. Otherwise, it won't line wrap, and the width is much too great for the forum tables.
Thanks, and let's see what others suggest.
Thanks for getting back to me, Adak. Please see the code below. Is this what you had in mind? Thanks.
Code:
/* pe6b_new.c -- Write a program that initializes
* a two-dimensional array-of-double and uses one
* of the copy functions from exercise 2 to copy
* it to a second two-dimensional array.
* (Because a two-dimensional array is an array
* of arrays, a one-dimensional copy function
* can be used with each subarray.) */
#include <stdio.h>
#define ROW 5
#define COL 5
/* compiler warnings did not refer to copy_arr(),
* but to show_arr().*/
void copy_arr(const double s[], double t[], int n);
/* declared 1st formal parameter as non-const */
void show_arr(double ptr[][COL], int row);
int main(void)
{
int i;
/* declared a const pointer to an array of 5 doubles */
const double (*ptr)[COL];
double source[ROW][COL] = {
{1.1,2.2,3.3,4.4,5.5},
{6.6,7.7,8.8,9.9,10.1},
{11.1, 12.1,13.1,14.1,15.1},
{16.1,17.1,18.1,19.1,20.1},
{21.1,22.1,23.1,24.1,25.1}
};
double target[ROW][COL];
for (i = 0; i < ROW; i++)
copy_arr(source[i], target[i], ROW);
printf("SOURCE\n");
/* assigned address of the 1st source array of 5 doubles to ptr */
ptr = source;
/* passed it to show_arr() */
show_arr(ptr, ROW);
printf("\nTARGET\n");
/* assigned address of the 1st source array of 5 doubles to ptr */
ptr = target;
/* passed it to show_arr() */
show_arr(ptr, ROW);
return 0;
}
void copy_arr(const double s[], double t[], int n)
{
int c;
for (c = 0; c < COL; c++)
t[c] = s[c];
}
void show_arr(double ptr[][COL], int row)
{
int r, c;
for (r = 0; r < row; r++)
for (c = 0; c < COL; c++)
printf("%g ", ptr[r][c]);
putchar('\n');
}
Code:
pe6b_new.c: In function 'main':
pe6b_new.c:38: warning: assignment from incompatible pointer type
pe6b_new.c:40: warning: passing argument 1 of 'show_arr' from incompatible point
er type
pe6b_new.c:17: note: expected 'double (*)[5]' but argument is of type 'const dou
ble (*)[5]'
pe6b_new.c:43: warning: assignment from incompatible pointer type
pe6b_new.c:45: warning: passing argument 1 of 'show_arr' from incompatible point
er type
pe6b_new.c:17: note: expected 'double (*)[5]' but argument is of type 'const dou
ble (*)[5]'