473,545 Members | 721 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

assigning values to an array after declaring it

Very basic question I'm afraid. Once an array has been declared, is there
a less tedious way of assigning values to its members than the following:

myarray[0]=8;
myarray[1]=3;
myarray[2]=4;
myarray[3]=0;
myarray[4]=0;
myarray[5]=1;
myarray[6]=8;
myarray[7]=8;
etc...

I can't assign values immediately on declaration because I want myarray
to be initialised differently according to various cases only determined
at runtime.

Thanks for any help. best regards -Eric

Nov 14 '05 #1
14 74796
Eric Bantock wrote:
Very basic question I'm afraid. Once an array has been declared, is there
a less tedious way of assigning values to its members than the following:

myarray[0]=8;
myarray[1]=3;
myarray[2]=4;
myarray[3]=0;
myarray[4]=0;
myarray[5]=1;
myarray[6]=8;
myarray[7]=8;
etc...

I can't assign values immediately on declaration because I want myarray
to be initialised differently according to various cases only determined
at runtime.

Thanks for any help. best regards -Eric


Here are some ideas:
1. Many constant arrays:
Declare constant arrays for each case in the program.
Copy the data from the constant array to the variable
depending on the circumstances. If the data won't change,
then use a pointer instead of an array.

2. Load data from a stream (file).
Prefer a text file to a binary file. Text files can be
easily created and updated using an editor. Binary files
are more difficult to create and maintain.

3. Load data from another source.
Some platforms have places that programs can store
their data, such as a registry or ROM. Accessing these
are off-topic for this newsgroup and not portable.
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Nov 14 '05 #2
On Wed, 16 Jun 2004 15:55:26 +0000 (UTC), in comp.lang.c , Eric Bantock
<eb@example.com > wrote:
Very basic question I'm afraid. Once an array has been declared, is there
a less tedious way of assigning values to its members

(than assigning values to members)

No.

Well, you could memcpy data into it, if you could be sure of byte order and
alignment constraints.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #3
Eric Bantock wrote:
Very basic question I'm afraid. Once an array has been declared, is there
a less tedious way of assigning values to its members than the following:

myarray[0]=8;
myarray[1]=3;
myarray[2]=4;
myarray[3]=0;
myarray[4]=0;
myarray[5]=1;
myarray[6]=8;
myarray[7]=8;
etc...

I can't assign values immediately on declaration because I want myarray
to be initialised differently according to various cases only determined
at runtime.


You can use a loop:

for (i = 0; i < N; ++i)
myarray[i] = some_expression _probably_invol ving_i;

Of course, this approach requires that there is some method
behind the apparent madness of 8,3,4,...

If the array contents are not systematic or readily computed
but have been laboriously typed in from historical records of
molybdenum production in nineteenth-century Bolivia *but* there
are only a few such sets of data, you could carry a few pre-
initialized arrays around and then copy the chosen one into
myarray[] at run-time:

const SomeType data_sets[][N] = {
{ 8,3,4, ... },
{ 6,6,8, ... },
{ 4,9,2, ... },
...
};
SomeType myarray[N];
...
int k = index_of_chosen _data_set;
memcpy(myarray, data_sets[k], sizeof myarray);

It's hard to recommend one approach over the other (or
over alternative possibilities) without some notion of what
you're really trying to accomplish.

--
Er*********@sun .com

Nov 14 '05 #4
In <ca**********@u s23.unix.fas.ha rvard.edu> Eric Bantock <eb@example.com > writes:
Very basic question I'm afraid. Once an array has been declared, is there
a less tedious way of assigning values to its members than the following:

myarray[0]=8;
myarray[1]=3;
myarray[2]=4;
myarray[3]=0;
myarray[4]=0;
myarray[5]=1;
myarray[6]=8;
myarray[7]=8;
etc...

I can't assign values immediately on declaration because I want myarray
to be initialised differently according to various cases only determined
at runtime.


If there are only a few possibilities, create an array for each one:

static const int ini1[] = { ... };
static const int ini2[] = { ... };
static const int ini3[] = { ... };

Then, if you have decided that ini2 is the right initialiser, you can do:

memcpy(myarray, ini2, sizeof myarray);

The other solution is a compound literal, but since this works in C99 only
I'm not advising it.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #5
Eric Bantock wrote:
Very basic question I'm afraid. Once an array has been declared, is there
a less tedious way of assigning values to its members than the following:

myarray[0]=8;
myarray[1]=3;
myarray[2]=4;
myarray[3]=0;
myarray[4]=0;
myarray[5]=1;
myarray[6]=8;
myarray[7]=8;
etc...

I can't assign values immediately on declaration because I want myarray
to be initialised differently according to various cases only determined
at runtime.

Thanks for any help. best regards -Eric


Initializers can be determined at runtime. Why can't you initialize
where you define it? You can use an inner scope.

void foo(void) {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
{
float arr[] = {a, b, c};
/* do something with arr */
}
}
Nov 14 '05 #6
"Mark McIntyre" <ma**********@s pamcop.net> wrote in message
news:2u******** *************** *********@4ax.c om...
On Wed, 16 Jun 2004 15:55:26 +0000 (UTC), in comp.lang.c , Eric Bantock
<eb@example.com > wrote:
Very basic question I'm afraid. Once an array has been declared, is there
a less tedious way of assigning values to its members (than assigning values to members)

No.

Well, you could memcpy data into it, if you could be sure of byte order

and alignment constraints.

But that wouldn't be *assigning* (as in "assigning values to its members"),
would it? IMHO, as usual, problem lies in
the problem definition, which seems not to define the problem, but to imply
the solution., and question turns out to be about the implementation of
particular
"suggested" solution. I hate it when my bosses are doing this to me. So the
1st
answer is perfectly correct (to my limited knowledge). Second one will
hopefully
clarify OP's question to himself. Though it may be considered irritating to
some participants here, I go by the old Chinese proverb: "Give a man a fish
and
you feed him for a day. Teach a man to fish, and you feed him for a
lifetime..",
even if someone only asks for one (topical) fish, (non-topical) reply in
some
circumstances can be more beneficial, in the long run.
Nov 14 '05 #7


Eric Bantock wrote:
Very basic question I'm afraid. Once an array has been declared, is there
a less tedious way of assigning values to its members than the following:

myarray[0]=8;
myarray[1]=3;
myarray[2]=4;
myarray[3]=0;
myarray[4]=0;
myarray[5]=1;
myarray[6]=8;
myarray[7]=8;
etc...

I can't assign values immediately on declaration because I want myarray
to be initialised differently according to various cases only determined
at runtime.

Thanks for any help. best regards -Eric


suggestion 1
create the other constant arrays. Then assign each value in a for loop
or with memcopy();

suggestion 2
create all the possible arrays, then use a pointer to choose the correct
one.
Nov 14 '05 #8
In <2u************ *************** *****@4ax.com> Mark McIntyre <ma**********@s pamcop.net> writes:
On Wed, 16 Jun 2004 15:55:26 +0000 (UTC), in comp.lang.c , Eric Bantock
<eb@example.co m> wrote:
Very basic question I'm afraid. Once an array has been declared, is there
a less tedious way of assigning values to its members(than assigning values to members)

No.


When Mark McIntyre says "no", it is usually safe to assume that the answer
is "yes". And vice versa.
Well, you could memcpy data into it, if you could be sure of byte order and ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^alignment constraints.

^^^^^^^^^^^^^^^ ^^^^^^

An idiotic statement, as one could expect from Mark. Since the
initialiser is compiled by the same compiler, there are no representation
issues at all. And memcpy() has NO alignment constraints: it is
actually the right way of handling assignments when the source is not
guaranteed to be aligned for its type (but this is a non-issue here,
anyway).

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #9
Eric Sosman <Er*********@su n.com> wrote:
Eric Bantock wrote:
Very basic question I'm afraid. Once an array has been declared, is there
a less tedious way of assigning values to its members than the following:
[snip] You can use a loop: for (i = 0; i < N; ++i)
myarray[i] = some_expression _probably_invol ving_i; Of course, this approach requires that there is some method
behind the apparent madness of 8,3,4,...
yes, and in this case unfortunately there is none.
const SomeType data_sets[][N] = {
{ 8,3,4, ... },
{ 6,6,8, ... },
{ 4,9,2, ... },
...
};
SomeType myarray[N];
...
int k = index_of_chosen _data_set;
memcpy(myarray, data_sets[k], sizeof myarray);


Thanks Eric (and Dan and others who suggested a similar approach) - this
is what I'll do. Actually, I have always wondered (but never been curious
enough to actually find out) exactly *why* C won't let you assign values
"all at once" to an array except at declaration. Can anyone explain?

Eric
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
8265
by: Ben | last post by:
Hi all, This may sound easy but I'm having trouble assigning values to array element. My problem is as follows: m = for o in m: # Here first o is 'Peter'.. I want to do something like this: Peter = 10
2
3369
by: Zitan Broth | last post by:
Greetings All, Running pg 7.3.4 and was reading: http://archives.postgresql.org/pgsql-interfaces/2003-09/msg00018.php . Basically want to assign values to an array and then a 2d array. However I can't get this to run in properly I get a syntax error (at or near ", output_txt_arr TEXT, output_str text ); CREATE OR REPLACE FUNCTION...
2
3260
by: ryoung | last post by:
I receive the following error when I attempt to assign values to a web service array. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: Line 553: AppDTO.zip = sZip Line 554: AppDTO.dob = sDOB '** line 555 is the highlighted row with the problem.
5
1646
by: Manuel Graune | last post by:
Hello, while trying to learn how to program using objects in python (up to now simple scripts were sufficient for my needs) I stumbled over the a problem while assigning values to an object. The following piece of code shows what I intend to do: <---snip--->
17
18743
by: Cliff | last post by:
Hi, I'm in the process of porting some code from a 3rd party and have hit a problem with the following: typedef struct { unsigned char Red; unsigned char Green; unsigned char Blue; }TBoxColour;
1
4768
by: Nightfarer | last post by:
Hello. I have a big trouble using System.Array class (it's the first time I use it) for a software I'm developing. I have a form with a textbox(numbers) and one button (done). Once the number is added to textbox clicking the done button saves the number in a variable (Numbers). The next form has a textbox(letter) and two buttons (add new,...
2
4036
by: Ray D. | last post by:
I want to set matrix A with the values below, but it produced a syntax error when I try to compile the commented code. I was told to use a for loop to do this (as shown below), but that really isn't possible considering I need these specific values. Is there a way to do this in one statement instead of multiple statements of A = ..., where...
6
2887
by: sumuka | last post by:
Hello, I'm doing a project in java and im not able to assign the values which are got from for loop to the 2-dimensional array. Can anyone tell me how to assign the values and print them? the code is: gr.getGridArray(); for (int s=0;s<=NoOfElevations;s++) for (int...
9
2147
by: J. Peng | last post by:
I just thought python's way of assigning value to a variable is really different to other language like C,perl. :) Below two ways (python and perl) are called "pass by reference", but they get different results. Yes I'm reading 'Core python programming', I know what happened, but just a little confused about it. $ cat t1.py def test(x):
0
7465
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7398
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7416
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5325
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4944
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3449
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1878
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
701
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.