2

In the book I am studying it says that if I pass a vector to a function, the name of the vector is always treated as a pointer. In fact it's so. But I can't understand why in the first function the const clause is allowed by the compiler, while in the second function (where I use pointers to search for the maximum value between the elements) no. In the functions I would simply like to protect against the modification of the vector.

#include <stdio.h>

int find_largest(const int a[], int n);
int find_largest_with_pointer(const int *vettore, int n);

int main(void) {
    int my_number[] = {5, 7, 90, 34, 12};
    int n = sizeof(my_number) / sizeof(my_number[0]);
    int *pmy_number = my_number;

    printf("%d\n", find_largest(my_number, n));
    printf("%d\n", find_largest(pmy_number, n));
    printf("%d\n", find_largest_with_pointer(my_number, n));
    printf("%d\n", find_largest_with_pointer(pmy_number, n));

    return 0;
}

int find_largest(const int a[], int n) {
    int i, max;
    max = a[0];

    for(i = 0; i < n; i++)
        if(a[i] > max)
            max = a[i];

    return max;
}

int find_largest_with_pointer(const int *vettore, int n) {
    int *i, max = *vettore;

    for(i = vettore; i < vettore + n; i++)
        if(*i > max)
            max = *i;

    return max;
}
Roberto Rocco
  • 450
  • 2
  • 11

2 Answers2

1

Since vettore is a pointer to const int, you must make i have the same type.

const int *i;
int max = *vettore;

for(i = vettore; i < vettore + n; i++)
jxh
  • 69,070
  • 8
  • 110
  • 193
0

Short Version: Adding a const qualifier will address the compiler warning.

int find_largest_with_pointer(const int *vettore, int n) {
//    int *i, max = *vettore;
    const int *i ;
    int max = *vettore;
    ...
}

Long Version:

In the second function, you use two variables. Expanding the code a little bit

   int *i ;l
   it max = a[0] ;
   for (
       i = vettore;
       i < vettore + n;
       i++
   ) { ... }

Note the line i = vettore, which will attempt to copy the 'const int * vettoreinto non-const 'int *i. This has the potential of allowing modification to the const vector (e.g. *i = 5), and the compiler complain:

c.c:33:11: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
     for(i = vettore; i < vettore + n; i++)

Solution is simple: add const qualifier on const int *i. See above.

dash-o
  • 13,723
  • 1
  • 10
  • 37