In higher level languages I would be able something similar to this example in C and it would be fine. However, when I compile this C example it complains bitterly. How can
In C99, using compound literals, you could do:
memcpy(values, (int[3]){1, 2, 3}, sizeof(int[3]));
or
int* values = (int[3]){1, 2, 3};
This works and optimizes better under gcc with -O3 (the compiler completely removes the code), whereas the memcpy forces the memory to be copied in all cases.
template <typename Array>
struct inner
{
Array x;
};
template <typename Array>
void assign(Array& lhs, const Array& rhs)
{
inner<Array>& l( (inner<Array>&)(lhs));
const inner<Array>& r( (inner<Array>&)(rhs));
l = r;
}
int main()
{
int x[100];
int y[100];
assign(x, y);
}
#include<stdio.h>
#include<stdlib.h>
#include<stdarg.h>
int *setarray(int *ar,char *str)
{
int offset,n,i=0;
while (sscanf(str, " %d%n", &n, &offset)==1)
{
ar[i]=n;
str+=offset;
i+=1;
}
return ar;
}
int *setarray2(int *ar,int num,...)
{
va_list valist;
int i;
va_start(valist, num);
for (i = 0; i < num; i++)
ar[i] = va_arg(valist, int);
va_end(valist);
return ar;
}
int main()
{
int *size=malloc(3*sizeof(int*)),i;
setarray(size,"1 2 3");
for(i=0;i<3;i++)
printf("%d\n",size[i]);
setarray2(size,3 ,4,5,6);
for(i=0;i<3;i++)
printf("%d\n",size[i]);
return 0;
}