1

If I want to create a vector of size components and I want all components to be 1, one way to do this is, of course, to use a for loop in this way

#include <stdio.h>

int main()
{
    int size=100;
    int array[size];
    for(int j=0; j<size; j++)
    {
        array[j]=1;
    }
}

But it doesn't look like the way programmers would do it. How can I do this vectorially, that is, without changing one element at a time?

1
  • 4
    It really depends. What is the initial value you want all elements to have? If it's zero then initialize it on definition. Otherwise there's memset to set the individual bytes (not elements). But no matter what you do, ultimately there will always be a loop somewhere, even if it's not explicitly in your own code. Commented Dec 13, 2022 at 22:57

1 Answer 1

2

I'm afraid there are no alternatives to the loop in standard C.

If gcc is an option you can use Designated initializers to initialize a range of elements to the same value:

int array[] = {[0 ... 99] = 1};
Sign up to request clarification or add additional context in comments.

4 Comments

I noticed that this will not work in case I want to provide the size as a parameter, rather than writing the numerical value "99" explicitly. Is there a way to make it work in that case?
You can use int array[100] = {[0 ... (sizeof array / sizeof array[0]) - 1] = 1};
Can this method be used if you don't know size until runtime?
@SimonGoater do you mean with a Variable-Length array, no, you can not: error: variable-sized object may not be initialized

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.