passing pointers

P

PengYu.UT

Hi,

I have the following two functions. However, the function printa gives
me a warning. If I delete "const" from its definition, I will not get
the warning. I'm wondering if there is anything wrong with compiler,
because the function printb works fine.

Best wishes,
Peng

#include <stdio.h>

void printa(const double (*a)[2]){//warning
//void printa(double (*a)[2]){//no warning
printf("Hello!\n");
}

void printb(const double *b){
printf("Hello!\n");
}

int main(int argc, char *argv[]){
double a[10][2];
double b[10];
printa(a);
printb(b);

return 0;
}
 
L

Lawrence Kirby

Hi,

I have the following two functions. However, the function printa gives
me a warning. If I delete "const" from its definition, I will not get
the warning. I'm wondering if there is anything wrong with compiler,
because the function printb works fine.

The compiler is correct, this is a wart in C's type system. An array can't
be specified as const, only its elements.
Best wishes,
Peng

#include <stdio.h>

void printa(const double (*a)[2]){//warning //void printa(double
(*a)[2]){//no warning
printf("Hello!\n");
}
}
void printb(const double *b){
printf("Hello!\n");
}
}
int main(int argc, char *argv[]){
double a[10][2];
double b[10];
printa(a);

Here you are trying to pass a pointer to an array of 2 doubles to a
function requiring a pointer to an array of 2 const doubles. C allows
conversion from a pointer to TYPE to a pointer to const TYPE. In this case
that would have to be to a pointer to a const array of double, which is
not possible in C. Conversion to a pointer to an array of const double
doesn't fit the rule so is invalid. This is a case where you just have to
forget about const or put a cast in.
printb(b);

This is fine because you are converting from a pointer to double to a
pointer to const double which fits the rule.

Lawrence
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top