0

I'm trying to protect the -a- array of the my_sum_array function from the changes. In the function block I do not make any changes to -a-, but I have a warning (warning: assignment to 'int *' from 'const int *' discards the qualifiers [-Wincompatible-pointer-types-discards-qualifiers]). I know I could remove const to make the program work, but I would like to understand if something is missing from me.

#include <stdio.h>

#define MAX 5

int my_sum_array(const int a[], int n);

int main(void) {
    int values[5] = {4, 7, 1, 7, 8};

    printf("The sum in my_sum_array is :%d\n", my_sum_array(values, MAX));

    return 0;
}

int my_sum_array(const int a[], int n) {
    int *p, sum = 0;

    for (p = a; p < a + n; p++)
        sum += *p;

    return sum;
}

Roberto Rocco
  • 450
  • 2
  • 11
  • 2
    You need to _add_ const somewhere. Look at the type of `p` in your function. – Mat Nov 09 '19 at 21:27
  • The problem is that merely creating an `int *` gives the rest of the code **license** to modify the data, even if the (current) implementation of the function doesn't do so. Consider what would happen if you passed `p` to a function accepting `int *` defined in another compilation unit. The compiler would then have no way to check that the data is not being modified. – user4815162342 Nov 09 '19 at 22:03

3 Answers3

2

The warning is caused by the assignment p = a in the for loop. The variable is defined as int *p, a pointer to non-const int. The warning is correct, "assignment to int * from const int * discards the qualifiers". It's as though you've casted away the constness of the a pointer parameter.

I'd change your function to:

int my_sum_array(const int a[], int n) {
    int sum = 0;

    for (const int *p = a; p < a + n; p++)
        sum += *p;

    return sum;
}

This defines p as a pointer-to-const, just like a, and also limits its lifetime to the for loop.

Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
1

Make your p pointer as:

    int const * p;

i.e.

here, p is a pointer to a const integer

0

Change type of p to:

const int *p;

So now you end up with:

const int * p;
int sum = 0;
smac89
  • 39,374
  • 15
  • 132
  • 179