E
Eric Laberge
Aloha!
This question is meant to be about C99 and unnamed compound objects. As I
read, if such a construct as
int *p = (int[]){0};
is used within a function, then it has "automatic storage duration
associated with the enclosing block".
So I tried the annexed code, and it compiles without a warning, and works as
I expected.
I'm mostly puzzled by the object lifetime, ie.: if I can reasonably use such
a construct for temporary initialisation, by passing it as a function
parameter and then memcpy'ing it to another variable. By it being declared
as a function parameter, is this function the "enclosing block" and as such
I will lose the ability to correctly pass it's pointer back to memcpy, or
is its scope the entire "main" function?
Before somebody asks why I don't directly call "myfunc" with "a" or "b" as
parameters, I'm trying to chain some array-modifying functions together,
and mostly simply experimenting some stuff.
Thanks, I like reading this group.
/* BOF */
/* Tried with "gcc -std=c99 -pedantic -Wall file.c" */
#include <stdio.h>
#include <string.h>
unsigned int* myfunc(unsigned int* buffer)
{
unsigned int i;
for (i = 0; i < 5; i++)
buffer = i;
return buffer;
}
int main(void)
{
unsigned int a[5];
unsigned int b[5];
unsigned int i;
memcpy(a, myfunc((unsigned int[5]){0}), sizeof a);
memcpy(b, myfunc((unsigned int[5]){0}), sizeof b);
for (i = 0; i < 5; i++)
printf("a[%d]=%d\tb[%d]=%d\n", i, a, i, b);
return 0;
}
/* EOF */
This question is meant to be about C99 and unnamed compound objects. As I
read, if such a construct as
int *p = (int[]){0};
is used within a function, then it has "automatic storage duration
associated with the enclosing block".
So I tried the annexed code, and it compiles without a warning, and works as
I expected.
I'm mostly puzzled by the object lifetime, ie.: if I can reasonably use such
a construct for temporary initialisation, by passing it as a function
parameter and then memcpy'ing it to another variable. By it being declared
as a function parameter, is this function the "enclosing block" and as such
I will lose the ability to correctly pass it's pointer back to memcpy, or
is its scope the entire "main" function?
Before somebody asks why I don't directly call "myfunc" with "a" or "b" as
parameters, I'm trying to chain some array-modifying functions together,
and mostly simply experimenting some stuff.
Thanks, I like reading this group.
/* BOF */
/* Tried with "gcc -std=c99 -pedantic -Wall file.c" */
#include <stdio.h>
#include <string.h>
unsigned int* myfunc(unsigned int* buffer)
{
unsigned int i;
for (i = 0; i < 5; i++)
buffer = i;
return buffer;
}
int main(void)
{
unsigned int a[5];
unsigned int b[5];
unsigned int i;
memcpy(a, myfunc((unsigned int[5]){0}), sizeof a);
memcpy(b, myfunc((unsigned int[5]){0}), sizeof b);
for (i = 0; i < 5; i++)
printf("a[%d]=%d\tb[%d]=%d\n", i, a, i, b);
return 0;
}
/* EOF */