-1
typedef struct {
    int a;
    int* b;
} foo_t;

int main (void){
    foo_t foo;
    int array[10];
    foo.b= &array[0];
}  

Here is a sample code. As you know, if we define a structure, this structure allocates a memory as its total capacity. In above case, it comes to me as if it overflows its capacity, this is right ? If I apply a static check, are there any problem with this? How does this work, please explain to me.

brhans
  • 14,723
  • 3
  • 35
  • 51
IHK
  • 99
  • 6
  • 6
    I’m voting to close this question because this is a general C programming question, not related to electrical engineering especially. Programming questions can be asked over at Stackoverflow.com, but they'll expect own debugging and code that actually compiles! – Marcus Müller Mar 21 '21 at 23:51
  • Is there anyway to port questions likes this from EESE to Stack Overflow? – Mitu Raj Mar 22 '21 at 08:52
  • If you want static checks, use a language with better static checking. –  Mar 22 '21 at 13:56
  • 1
    @MituRaj Moderators can migrate questions but it's burdensome since it usually involves mods on both target and destination sites. Easier then if the OP just copy/paste and ask it on the correct place. This question is on-topic on Stack Overflow as-is, so in this case it would be easy. – Lundin Mar 22 '21 at 15:02

1 Answers1

4

int* b is just a pointer. The structure will have sufficient space to store a single pointer value in this field.

&array[0] is also just a pointer, and so will fit within the structure field.

The value you are assigning is the address of the start of the array. It is not the array. It may point to the array, but once the reference is taken, the compiler doesn't know this as you lose all information about the size of the memory that you are pointing to.

There is no overflow of memory.


As a side note, &array[0] is equivalent to just array. Both are a pointer to the same thing. The type pointer[size] simply allocates space of sizeof(type)*size, and then creates a variable called pointer which stores the address of it.

&array[1] would be equivalent to array + 1.

Tom Carpenter
  • 65,995
  • 3
  • 145
  • 204
  • Okey I knew this but, even so I want to ask. Btw, do you know any free static code analyzer in eclipse store ? Have you ever used ? – IHK Mar 21 '21 at 22:33
  • Pedantically, &array[0] is not the same as array, it depends on the operator used in the expression. Arrays do not always decay into a pointer to the first element. For example printf("%zu\n", sizeof array); prints 40 in this case but printf("%zu\n", sizeof arr[0]); prints 4 and sizeof &*arr[0] also prints 4. – Lundin Mar 22 '21 at 15:08