tags:

views:

141

answers:

8

Hello,

I want to do this:

char a[5];

//run some code here
//then

a[]={0,1,2,3,4};  //**compiler doesn't like it

but I don't want to do this:

a[0]=0;
a[1]=1;
a[2]=2;
a[3]=3;
a[4]=4;

Do you know any way to populate an array at run time with numbers, not a string (i.e., not a ="hello"), in one go, instead of defining every element individually?

Thanks,

Raed

+4  A: 

No, there is no way of doing that. You need to use a loop, or assign each value individually.

anon
A: 

Have you tried this:

char a[] = {0, 1, 2, 3, 4};

The compiler will automatically set this to be an array of 5, initialized with each element corresponding to their value and index.

Edit: Looking at it again, I realized what you were looking for. In short the compiler will not accept this.

Hope this helps, Best regards, Tom.

tommieb75
+1  A: 

You could do memcpy(a, "\0\1\2\3\4", 5);, but it's bad practice and coding style.

Short of that no you can't.

Andreas Bonini
A: 

sprintf( a, "%d%d%d%d%d", 0,1,2,3,4 );

Changed my answer.

fixmedaily
If you're going to do this, declare a as `char a[6]` - you need an extra byte for the NULL character strcpy will append.
Graeme Perrow
Your new answer requires the extra byte as well.
Graeme Perrow
It also puts 48 in instead of 0: %d prints the ASCII value. You could probably fix this (and the extra byte problem) with: `snprintf(a,5,"%c%c%c%c%c",0,1,...`, but I'm not suggesting it's a good idea. Stick with memcpy, a loop or individual assignment.
Al
@fixmedaily: This doesn't do anything near what the OP wants.
Alok
+2  A: 

Well, you could set up a template to be copied into it later:

#include <stdio.h>
#include <string.h>

static char a_src[] = {0,10,20,30,40};
int main() {
    char a[5];

    memcpy (a, a_src, sizeof(a_src));
    printf ("%d\n", a[3]);
    return 0;
}

Outputs 30 when run.

But this is still techically sourcing the data at compile-time. If you really want to do it at runtime (with calculated values), you need to do it element by element.

paxdiablo
+2  A: 

char a[5];

//run some code here
//then

static const char a_01234[sizeof(a)] = {0,1,2,3,4};
memcpy(a, a_01234, sizeof(a));
vitaly.v.ch
A: 

You could use a pointer and reference it as an array.

char * a;
char b[5] = {0,1,2,3,4};
char c[5] = {5,6,7,8,9};

//run some code here
//then

a = b;  // "Populate" the "array"

// Then reference a using array notation
printf ("%d\n", a[3]);  // Print the number 3

// run some more code

a = c;  // "Populate the "array" with some new values
printf ("%d\n", a[3]);  // Print the number 8
semaj
A: 

Using C99 compound literals (supported by GCC but not MSVC),

char a[5];

//run some code here
//then

memcpy(a, (char[]){0,1,2,3,4}, sizeof(a));
ephemient