r/C_Programming • u/Scared-Objective3768 • Aug 15 '26
Beginner using C Programming a Modern Approach
I understand the problem but the error message I do not understand the error message
Write the following function:
bool search(const int a[], int n, int key);
a is an array to be searched, n is the number of elements in the array, and key is the search
key. search should return true if key matches some element of a, and false if it
doesn’t. Use pointer arithmetic—not subscripting—to visit array elements.
`Here is my solution:
bool search(const int a[], int n, int key) {
int *p;
for (p = a; p < a + n; p++) {
if (*p == key) {
return true;
}
}
return false;
}
`
I get an error message of 'assignment discards ‘const’ qualifier from pointer target type'
I remove the const from the parameter list and the program works fine. Can yall explain what the error message means. I am compiling with gcc btw i dunno if that helps. sorry for bad formatting im kinda new to this.
thanks
•
u/mikeblas Aug 18 '26
Please correctly format your code
11
u/ByMeno Aug 15 '26
you are just viewing the items and comparing them not changing them so in the input you put const which is correct (and note that in function arguments [] does not mean anything different than normal pointer)
Now you are assigning it to p but p has the type of '
int *' not 'const int *' which means this pointer can dereference and change the underlying value at that address for fixing that just put aconst int *p;And for const if a type has:
type const var;const type var;those two mean the underlying value wont change
put for pointers it will be
type * const ptr;which means the pointer wont change but value can change
if both of them should not change
const type *const ptr;or
type const *const ptr;are usable
5
u/sciencekm Aug 15 '26
"
int *p;" needs to be "const int *p;" to match the "const int a[]"2
u/heneriss Aug 15 '26
because you are pointing to a memory that cannot be modified.