2

I've the following struct:

typedef struct{
    int freq;
    char val;
} Char; // alias

And I need to create a buffer (pointer) to a certain number of Char as follows:

Char* chars  = calloc(256, sizeof(Char));

And I would like to initialize freq to -1 for all Char structs in chars. Is it possible to do it without a loop?

nbro
  • 15,395
  • 32
  • 113
  • 196
  • `memset`, if you don't mind having `-1` or some other junk in `val`. – Eugene Sh. Mar 04 '16 at 22:31
  • @EugeneSh. `val` can be anything provided it's a `char`, of course, but `-1` is not a char, or is it? Actually I was forgetting, when I declare a variable with `char val`, I am declaring a 8 bit signed int, right? Which means that -1 will be considered a `char`, right? – nbro Mar 04 '16 at 22:33
  • 1
    Anyway, it's a bad idea, as `memset` can fill with byte value only. And in order to fill `int's you will have to assume a specific negative numbers representations, which is not portable. – Eugene Sh. Mar 04 '16 at 22:35
  • 3
    @nbro `char` is not guaranteed to be signed, it's implementation defined. It could be unsigned. – jpw Mar 04 '16 at 22:37
  • 1
    What's wrong with a loop? That's what they're for. Many other languages may have some fancy syntax for specifying the loop in a shorter way, but they all end up looping, and the compiler will do that in whatever way is most efficient. – Lee Daniel Crocker Mar 04 '16 at 23:21

1 Answers1

2

If you use GCC you can do Char s[256] = {[0 ... 255] = {-1, 0}};

{-1, 0} is the structure initialization

EDIT: You can have a look at this post: How to initialize all members of an array to the same value? It would give great hints :)

Community
  • 1
  • 1
Alexis Clarembeau
  • 2,776
  • 14
  • 27
  • OK, now you are talking... Update: Actually the OP is asking about dynamically allocated array, so it won't work... But it's a good pointer. – Eugene Sh. Mar 04 '16 at 22:44
  • The links gives the function: `void array_init( void *start, size_t element_size, size_t elements, void *initval ){ memcpy( start, initval, element_size ); memcpy( (char*)start+element_size, start, element_size*(elements-1) ); }` It can be used to dynamically allocate the array :) – Alexis Clarembeau Mar 04 '16 at 23:14