Re: arrays, pointers, and constness

From: Axel Naumann <Axel.Naumann_at_cern.ch>
Date: Fri, 09 Nov 2007 17:04:15 +0100


Hi Annalisa,

Annalisa De Caro wrote:
> can anyone explain me what the difference is
> in between the following two line sets:
> 1)
> Float_t *ccc;
> for (Int_t ii=0; ii<3; ii++) ccc[ii] = fgkAl3parameters[ii];
> 2)
> const Float_t fgkAl3parameters[3] = {3., 4., 0.1};
> Float_t *ccc = &fgkAl3parameters;

Case 1: let's take the iteration where ii==0. It puts the value of fgkAl3parameters[ii] into a new position in memory ("=", namely where ccc points to plus 0 times the memory size that a Float_t needs (that's what "[0]" stands for). But where does ccc point to? It's random! You never set it to any value! In case 2, ccc is set to point to the memory address of fgkAl3parameters, so that's fine.

> And again,
> I made a macro (attached to this email):
> this macro contains two methods,
> one per each of the previously reported possibilities.
>
> When I made the following:
> .L proviamo.C
> the compilation is ok,
> but the first method execution ends with a segmentation violation

You now know why.

> and the execution of the second one ends correctly.
That's because CINT is too nice - it does not check your code properly. If you run ".L proviamo.C+" or ".L proviamo.C++", your compiler gets invoked which is better in spotting code errors. And so it complains:

> When I made the following:
> .L proviamo.C++
> the compilation stops with the following message:
> ./proviamo.C:31: error: cannot convert `const Float_t (*)[3]' to `Float_t*' in initialization

You have an array of "const Float_t"s, and you try to set ccc (a pointer to a Float_t) by making it point to the array. That won't work; ccc doesn't respect the const-ness of the array values: the array has const Float_t, ccc doesn't. Make it "const Float_t *ccc" instead.

> If I comment the second method content,
> the compilation ends correctly
> and the first method execution also.

If that's really the case then you're extremely lucky - ccc is not initialized, so it should usually just crash. But maybe ccc was accidentally, randomly pointing to some valid region of memory....

Cheers, Axel. Received on Fri Nov 09 2007 - 17:04:37 CET

This archive was generated by hypermail 2.2.0 : Fri Nov 09 2007 - 23:50:01 CET