C how to initialize array

C how to initialize array

How to initialize an array in C++ objects

Don’t overlook the obvious solution, though:

I tried something like this:

The obvious in this case is not so obvious. I really would like the initiation of my array to be more dynamic as well.

This looked funky to me to, and so to the compiler:

This also did not work:

I have been doing really good and learning what does not work, but not so good learning what does work.

So, how do I used initialization lists for an array inside a class?

I have been trying to figure out how to do this for some time now and am very stuck, I have a number of these kinds of lists I need to make for my app.

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You need to initialize the array in the constructor initialization list

..\src\Something.cpp:6:51: sorry, unimplemented: non-static data member initializers

C++11 also adds supports for inline initialization of non-static member variables, but as the above error message states, your compiler has not implemented this yet.

In your last example, you’re trying to add static initialization to a non-static member. If you want the array to be a static member of the class, you could try something like this:

If you want to add a class member, you could try making the static array const and copy it into the member array in the constructor.

It is possible to initialize array values of the array in size the main function like this:

Initialising arrays in C++

For example, take the code:

Does NULLing the entire array create a performance impact over using the array without initialising it?

10 Answers 10

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

I assume a stack initialization because static arrays are auto-initialized.
G++ output

So, you initialize with <'\0'>and a call to memset is done, so yes, you have a performance hit.

If the variable is a global or static, then its data is typically stored verbatim in the compiled executable. So, your char arrBuffer[1024] will increase executable size by 1024 bytes. Initializing it will ensure the executable contains your data instead of the default 0’s or whatever the compiler chooses. When the program starts, no processing is required to initialize the variables.

On the other hand, variables on the stack, such as non-static local function variables, are not stored in the executable the same way. Instead, on function entry the space is allocated on the stack and a memcpy places the data into the variable, thereby impacting performance.

The rule is that variables should be set before they’re used.

You do not have to explicitly initialize them on creation if you know you will be setting them elsewhere before use.

For example, the following code is perfectly okay:

In that case, it’s wasteful to initialize the array at the point of its creation.

As to whether there’s a performance penalty, it depends partially on where your variable is defined and partially on the execution environment.

The C standard guarantees that variables defined with static storage duration (either at file level or as statics in a function) are first initialized to a bit pattern of all zeros, then set to their respective initialized values.

It does not mandate how that second step is done. A typical way is to just have the compiler itself create the initialized variable and place it in the executable so that it’s initialized by virtue of the fact that the executable is loaded. This will have no performance impact (for initialization, obviously it will have some impact for program load).

Of course, an implementation may wish to save space in the executable and initialize those variables with code (before main is called). This will have a performance impact but it’s likely to be minuscule.

As to those variables with automatic storage duration (local variables and such), they’re never implicitly initialized unless you assign something to them, so there will also be a performance penalty for that. By «never implicitly initialized», I mean the code segment:

will result in x[] having indeterminate values. But since:

may simply result in a 1000-integer memcpy-type operation (more likely memset for that case), this will likely to be fast as well. You just need to keep in mind that the initialization will happen every time that function is called.

Declaring and initializing arrays in C

Is there a way to declare first and then initialize an array in C?

So far I have been initializing an array like this:

But I need to do something like this

C how to initialize array. Смотреть фото C how to initialize array. Смотреть картинку C how to initialize array. Картинка про C how to initialize array. Фото C how to initialize array

8 Answers 8

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

In C99 you can do it using a compound literal in combination with memcpy

(assuming that the size of the source and the size of the target is the same).

In C89/90 you can emulate that by declaring an additional «source» array

No, you can’t set them to arbitrary values in one statement (unless done as part of the declaration).

You can either do it with code, something like:

or (if there’s a formula):

The other possibility is to keep around some templates that are set at declaration time and use them to initialise your array, something like:

This has the advantage of (most likely) being faster and allows you to create smaller arrays than the templates. I’ve used this method in situations where I have to re-initialise an array fast but to a specific state (if the state were all zeros, I would just use memset ).

You can even localise it to an initialisation function:

The static array will (almost certainly) be created at compile time so there will be no run-time cost for that, and the memcpy should be blindingly fast, likely faster than 1,229 assignment statements but very definitely less typing on your part :-).

Array initialization

When initializing an object of array type, the initializer must be either a string literal (optionally enclosed in braces) or be a brace-enclosed list of initialized for array members:

= string-literal(1)
= <expression , . >(2)(until C99)
= <designator (optional) expression , . >(2)(since C99)
= <>(3)(since C23)

All array elements that are not initialized explicitly are empty-initialized.

Contents

[edit] Initialization from strings

String literal (optionally enclosed in braces) may be used as the initializer for an array of matching type:

Successive bytes of the string literal or wide characters of the wide string literal, including the terminating null byte/character, initialize the elements of the array:

If the size of the array is known, it may be one less than the size of the string literal, in which case the terminating null character is ignored:

[edit] Initialization from brace-enclosed lists

It’s an error to provide more initializers than elements when initializing an array of known size (except when initializing character arrays from string literals).

A designator causes the following initializer to initialize of the array element described by the designator. Initialization then continues forward in order, beginning with the next element after the one described by the designator.

When initializing an array of unknown size, the largest subscript for which an initializer is specified determines the size of the array being declared.

[edit] Nested arrays

If the elements of an array are arrays, structs, or unions, the corresponding initializers in the brace-enclosed list of initializers are any initializers that are valid for those members, except that their braces may be omitted as follows:

If the nested initializer begins with an opening brace, the entire nested initializer up to its closing brace initializes the corresponding array element:

If the nested initializer does not begin with an opening brace, only enough initializers from the list are taken to account for the elements or members of the sub-array, struct or union; any remaining initializers are left to initialize the next array element:

Array designators may be nested; the bracketed constant expression for nested arrays follows the bracketed constant expression for the outer array:

[edit] Notes

The order of evaluation of subexpressions in an array initializer is indeterminately sequenced in C (but not in C++ since C++11):

In C, the braced list of an initializer cannot be empty. C++ allows empty list:

An empty initializer can be used to initialize an array:

As with all other initialization, every expression in the initializer list must be a constant expression when initializing arrays of static or thread-local storage duration:

How to Initialize array in c?

I have written this code but on compilation i’m getting message «invalid expression» for the following statement

C how to initialize array. Смотреть фото C how to initialize array. Смотреть картинку C how to initialize array. Картинка про C how to initialize array. Фото C how to initialize array

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You can only do that when declaring and assigning a variable at the same time. You cannot do so afterwards. You could create another variable and assign that, though:

This might make problems with sizeof(address) afterwards; if you need that it’s probably better to just use another variable.

If you want to assign a whole array in one go (and not just get a reference to it) you could wrap it into a struct like this:

C how to initialize array. Смотреть фото C how to initialize array. Смотреть картинку C how to initialize array. Картинка про C how to initialize array. Фото C how to initialize array

Within the gameOver() function, you’re trying to assign all of the values of an array with a single assignment. This isn’t legal. You would normally use memcpy() or a loop to set the values one by one. This is often done by declaring and initialising a temporary array and copying the contents into the array you want to re-initialise.

The name of your destination variable is a bit dubious, though. Typically if something was called address I would expect it to be a pointer. If you meant it to be a pointer, and if you don’t mean to change the values that address points to, then your assignment would be nearly legal.

Making tmp[] const (and making address a pointer to const) allows the compiler to put the data in a read-only segment, which might mean ROM on an embedded system.

However, the code that is shown does not look like it needs copying, and elements need be no larger than a char to hold all their values. The temporary array could just as easily be the working array:

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *