Reputation: 13
I am trying to make a code where i send an array from a function to be erased, i do not know the length of the array, since it will be declared after a variable that will be typed by the user, so im trying to send as a pointer. but i constantly get an error. the code looks like this
int apagaarray(int *array,int l,int c){
for(int i=0;i<l;i++){
for(int j=0;j<c;j++){
array[i][j]=0;
}
}
}
but it returns an error:
error: subscripted value is neither array nor pointer nor vector|
what is going on ? is there a way to send an array to a function without having the parameters ?
Upvotes: 0
Views: 264
Reputation: 675
#include <stdio.h>
void printArray(int *arr, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// Use address to refer the array element.
printf("%d ", *(arr + (i * cols) + j));
}
printf("\n");
}
}
void eraseArray(int *arr, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// Use address to refer the array element.
*(arr + (i * cols) + j) = 0;
}
}
}
int main()
{
int arr[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
printArray((int *)arr, 3, 3); // Cast array to 1-dim array
eraseArray((int *)arr, 3, 3); // Cast array to 1-dim array
printArray((int *)arr, 3, 3); // Cast array to 1-dim array
return 0;
}
Cast the array to one-dimensional array and pass it.
You can change the value too, Since you are passing pointers instead of values.
Upvotes: 0
Reputation: 75
i think it would be the most correct this way:
int func(int **array, int l, int c)
{
for (int i = 0; i < l; i++) {
for (int j = 0; j < c; j++) {
array[i][j] = 0;
}
}
}
int main(void)
{
int l = 5, c = 5;
int **array = malloc(sizeof(int *) * l);
for (int i = 0; i < l; i++) {
array[i] = malloc(sizeof(int) * c);
for (int j = 0; j < c; j++) {
array[i][j] = j+1;
}
}
//print something
printf("%d\n", array[3][3]);
//empty it
// make note that im passing **array <= a ptr of ptr
func(array, l, c);
return 0;
}
not my usual self to provide a code but please try to run through it and see if that answers
Upvotes: 2
Reputation: 672
Matrices should be represented as follows:
Either int **array
or int *array[]
The correct function is:
int apagaarray(int **array,int l,int c){
for(int i=0;i<l;i++){
for(int j=0;j<c;j++){
array[i][j]=0;
}
}
}
Upvotes: 1