I am trying to implement a simple function that assigns the values of one array to another, but I keep getting an error
program.c:90:14: error: incompatible pointer types passing 'longint_t' (aka 'int [3]') to parameter of type 'longint_t *' (aka 'int (*)[3]'); take the address with & [-Werror,-Wincompatible-pointer-types]
My initial though behind this is that it should take 2 longint_t value, usually one will be empty or all zeroes, but not always, and another longint_t value and assign all the values of the second array to the first.
in the end, the variable vars should be of the form
[
[0,0,0],
[0,0,0],
.
.
. 26 arrays of [0,0,0]
]
here’s my bit of code:
#include <stdio.h>
#include <stdlib.h>
#define INTSIZE 3 /* max number of digits per integer value */
#define NVARS 26 /* number of different variables */
typedef int longint_t[INTSIZE];
void do_assign(longint_t *var1, longint_t *var2);
void zero_vars(longint_t vars[]);
/* Main program controls all the action
*/
int
main(int argc, char *argv[]) {
longint_t vars[NVARS];
zero_vars(vars);
for (int i=0; i<NVARS; i++){
for (int j=0; j<3;j++){
//printf("%d",vars[i][j]);
}
}
return 0;
}
void
zero_vars(longint_t vars[]) {
int i;
longint_t zero = {0};
for (i=0; i<26; i++) {
do_assign(vars[i], &zero);
}
return;
}
void
do_assign(longint_t *var1, longint_t *var2) {
for (int i=0; i<=3; i++){
*var1[i] = *var2[i];
}
}
any help would be appreciated thanks!
>Solution :
Pointers to arrays is a niche C topic, which is very confusing due to array-to-pointer decay.
Your do_assign function should assign one array to another (but it’s buggy; see below). It receives pointers to the arrays.
Your zero_vars function should initialize a 2-D array (array of arrays). It also receives a pointer to an array (this is what the compiler thinks, due to the decay rules). But it gives this pointer a different meaning — it’s a pointer to the first element of the array. This array has NVARS elements, each one of which is an array of INTSIZE integers. Confusing!
In your zero_vars implementation, vars[i] is an array. However, do_assign receives a pointer to an array! So you should take its address:
do_assign(&vars[i], &zero);
However, in your do_assign implementation, you should dereference your pointers:
(*var1)[i] = (*var2)[i];
You dereference the pointer first, and index the result afterwards. Due to operator precedence rules, you should specify the order of these operations, explicitly.