Re: const variables
- From: Marston <shejo284@xxxxxxxxx>
- Date: Sat, 2 May 2009 10:21:54 -0700 (PDT)
On May 1, 11:06 pm, Martin Ambuhl <mamb...@xxxxxxxxxxxxx> wrote:
Sheldon wrote:
Hi,
I have a function defined in the netcdf library as :
int nc_put_att_short (int ncid, int varid, const char *name,
nc_type xtype, size_t len, const short *sp);
Where the 5th argument is a pointer to short constant variable. In my
case this variable is a rather large array.
You probably mean the sixth argument: the fifth argument is 'size_t len'.
When I created and initialized the array I had to assign data to the
array before calling the function above.
How can I make my array match what this function is asking for, i.e. a
const short pointer?
It 'matches' already. The prototype only says that the function will
treat whatever sp points to as const.
Look at the following code and try to compile with a reasonably high
level of diagnostics:
#include <stdio.h>
void foo1(size_t n, const short *v); /* leaves v alone */
void foo2(size_t n, const short *v); /* tries to change v */
int main(void)
{
short array[] = { 3, 4, 5 };
size_t size = sizeof array / sizeof *array;
foo1(size, array);
foo2(size, array);
foo1(size, array);
return 0;
}
void foo1(size_t n, const short *v)
{ /* leaves v alone */
size_t i;
printf("foo1 just prints the contents of the array\n");
for (i = 0; i < n; i++)
printf("v[%zu] = %d\n", i, v[i]); /* this should _not_ give a
diagnostic */
putchar('\n');
}
void foo2(size_t n, const short *v)
{ /* tries to change v */
size_t i;
for (i = 0; i < n; i++)
v[i] = i * (i + 2); /* this line should give a diagnostic,
since this is an assignment to a
read-only location. */
}
I have several arrays to write so I store them in a struct. So my
pointer is of type: struct data *ptr and I have to then call the
above function to write the data.
My question is how do I make ptr->array a variable of type const short
*sp?
There is no need to do so.
Thanks. I see the point. Very informative.
/Mmm
.
- References:
- const variables
- From: Sheldon
- Re: const variables
- From: Martin Ambuhl
- const variables
- Prev by Date: Re: bits and good habits
- Next by Date: Arrays and pointers
- Previous by thread: Re: const variables
- Next by thread: End of the Epoch
- Index(es):
Relevant Pages
|