Solved

Quick question: Loop through int names

Posted on 2004-04-28
15
384 Views
Last Modified: 2010-08-05
Hi,
just a quick problem that appears quite simple but is giving me trouble.  All I want to do is loop through a group of int names and assign then a value.  For example the int names are: int name1,name2,name3,name4 and the values to be assigned are 1,2,3,4.  Is there anyway to loop through the names of the ints and assign them the correct value.  Any ideas on how to correct below?. Thanks.
 

for(int value=1;value<5;value++){
name+1=value;
}
0
Comment
Question by:everton690
  • 4
  • 3
  • 3
  • +4
15 Comments
 

Author Comment

by:everton690
ID: 10937048
correction!

above should be something like:
for(int value=1;value<5;value++){
name+value=value;
}




0
 
LVL 7

Expert Comment

by:leflon
ID: 10937101
Hi everton690,

from the code you posted it seems you are working in something like C/C++ language environment. correct??

leflon
0
 
LVL 10

Expert Comment

by:anv
ID: 10937104
U can Use Arrays.. that wud make it easier
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 10937142
Yep...

for(int value=1;value<5;value++){
int name[value]=value;
}

If you want name1, name2 ...then you have to make as Strings...by concatenating....
0
 
LVL 10

Assisted Solution

by:imrancs
imrancs earned 50 total points
ID: 10937156
i think the only way to do this is to use the Arrays as anv told

int name[5];

for(int value=1;value<5;value++){
name[value]=value;
}

it can be shown as

name[0] = 0
name[1] = 1
name[2] = 2
name[3] = 3
name[4] = 4

Imran
0
 
LVL 30

Assisted Solution

by:mayankeagle
mayankeagle earned 50 total points
ID: 10938338
Looks a little live Javascript to me ;-)

var val ;

for ( val = 1 ; val < 5 ; val ++ )
  eval ( "document.form.name" + val ).value = val ;

I don't see a way of accessing the integer-names that you've declared in any other way. It would be like compiling your own code yourself ;-) if you have int name1, name2, name3,  name4, name5.... how long can you go on reading and accessing the variables?

I think there is a way to do that in C as well (name <operator> 1 would give you the identifier name1), but unfortunately, I forgot :-(

If its Java and if all the integers are class-members, then you could try using reflection. Using reflection, you will be able to access all class-members and assign values to them in a loop.

The simplest approach to this in any language is arrays, of course. Would be glad if you could explain a little more as to what you want and in which language. I'm sure there's also an alternative to what you want, in terms of design.
0
 
LVL 1

Accepted Solution

by:
logicTRANCE earned 100 total points
ID: 10943063
The following should work alrite, it's pointer power afterall! ;-)

int name1, name2, name3, name4;
int *nameptr = &name1;

for(int value=0;value<4;value++){
*(nameptr+value) = value+1;
}

-------------------------------------------------------------------------
if you don't like pointers, then better use arrays; something like:

int name[4];
for(int value=1; value<5; value++)
{
   name[value-1] = value;       //note, in arrays (and for that matter everywhere in C/C++),                                                    //counting starts from 0, so use [value-1] and not value
}

//if you use name[value] in the above code, the 0th array element will be wasted and there will also be array overflow as name[value] when value=4 will use 4th array element i.e. 0,1,2,3,4th
but since we have allocated only 4 integers in the array (int name[4]), this will mean we are assigning value to a memory location that hasn't been allocated to our programme!
while declaring array, we use int name[4] because we want 4 elements in the array, i.e. 1,2,3,4 NOTE: here counting starts from 1 as against 0!!

Happy Programming!
-logicTRANCE
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 30

Expert Comment

by:mayankeagle
ID: 10946202
Well, but we're assuming that name1, name2, name3, name4 are allocated contiguous memory locations when they are allocated. What if they're not? The array approach is better.
0
 

Author Comment

by:everton690
ID: 10946920
Thanks to all who contributed. I think I will use the poiner method although using an array would also be effective

Cheers,
everton690.
0
 
LVL 7

Expert Comment

by:leflon
ID: 10947094
everton690,
i would really recommend using the array way. using the pointer way can get you in trouble
if i take a look at my stack (where the vars name1 ... name4 are allocated) the order looks something like
       address                    var
      0x0012ff80               ??????   <---------------------------------------------|
      0x0012ff7c               name1            <-   nameptr      -> nameptr++ ---
      0x0012ff78               name2
      0x0012ff74               name3
      0x0012ff70               name4
          .......

nameptr points to the address where var name1 is lying on the stack. incrementing the ptr will not bring you to name2 but to the address 0x0012ff80.
nobody knows what info is lying at that address. you can do real havoc to your prog if you now write something to this address. your prog may crash (which would be the best you can get) or just change some data belonging to a different part of your prog (very bad, ugly error, hard to detect in the long run). as mayankeagle said using this pointer method bases on assumption about the way the vars are allocated. i won' t rely on this.

do a little experimenting with pointers and the order you define the vars.
you will see using the array is the better and more secure way.

leflon
0
 

Author Comment

by:everton690
ID: 10947213
Thanks for the advice leflon, you saved a lot of my hair from almost certainly being pulled out while searching for errors that the pointer method would have introduced,
            Cheers and thanks,
            everton690
0
 
LVL 1

Expert Comment

by:logicTRANCE
ID: 10948461
leflon:
You are right.

if i use something like:
char *abc = "Hello";
strcpy(abc+strlen(abc), "World!");
printf("\n%s",abc);

this piece of code works perfectly and prints HelloWorld!

but:
char abc1='H', abc2='e', abc3='l';
char abcptr = &abc;
for(int i=0; i<3; i++)
{
  printf("%c",*(abcptr+i));
}
will printf--->   H<garbage><garbage>

so can we reliably say that when independent variables are allocated, they are allocated one by one starting at higner memory address in stack like:
3000  abc1
2999  abc2
2998  abc3

whereas when memory is allocated as char array, it is allocated in bulk and the array name is made to point to the lower stack address like:

3000  abc[2]
2999  abc[1]
2998  abc[0]   <---- using only abc will point here? i.e. abc without the subscript index?

in that case, doing strcpy on abc resulting in abc being larger than allocated array length will mean some other variables/unallocated space in higher memory of stack is overwritten, right?
i.e. in the above case, strcpy(abc,"HELLO"); will result in something like:

3002  'L'    <unknown>        ----these are illegal assignments that compiler wont catch
3001  'L'    <unknown>        ----i.e. array overflow
3000  'L'    abc[2]
2999  'E'    abc[1]
2998  'H'    abc[0]

Please tell me if my analysis is correct, this will help everyone in using pointers and debugging!
;-)

Happy Programming!
Regards
-logicTRANCE
0
 
LVL 1

Expert Comment

by:logicTRANCE
ID: 10948496
and everton690, really sorry for misleading...i'll double check from now on...but i hope someone clarifies my above query..hope that helps all!

-logicTRANCE
0
 
LVL 7

Expert Comment

by:leflon
ID: 10948836
@logicTRANCE

> char *abc = "Hello";
> strcpy(abc+strlen(abc), "World!");
> printf("\n%s",abc);

is 'evil' out of the same reasons you stated in

> 3002  'L'    <unknown>        ----these are illegal assignments that compiler wont catch
> 3001  'L'    <unknown>        ----i.e. array overflow
> 3000  'L'    abc[2]
> 2999  'E'    abc[1]
> 2998  'H'    abc[0]

there is no difference if you assign it by array-assignment or by copying it, as you stated you overwrite memory not belonging to the var. it is sheer luck that it didn't crash or misbehave.

the order a variable will be placed on the stack depends on the order they are defined in the prog.
  int a,b,c;
will probably look like
  1008  a
  1004  b
  1000  c
as the line is interpreted right to left (c -> b -> a).
while
  int a;
  int b;
  int c;
should give something like
  1008  c
  1004  b
  1000  a
(a -> b -> c)

> 3000  abc[2]
> 2999  abc[1]
> 2998  abc[0]   <---- using only abc will point here? i.e. abc without the subscript index?
yepp!

relying on the order of vars in memory is not a way very good thing. try to avoid it - no, don't do it at all

cheers
leflon
0
 
LVL 1

Expert Comment

by:logicTRANCE
ID: 10952271
hi leflon
this is what you wrote:
>int a,b,c;
>will probably look like
>  1008  a
>  1004  b
>  1000  c
>as the line is interpreted right to left (c -> b -> a).
>while
>  int a;
>  int b;
>  int c;
>should give something like
>  1008  c
>  1004  b
>  1000  a
>(a -> b -> c)

i'd like to correct you:
int a,b,c; will look as you said alrite:
 1008  a
 1004  b
 1000  c
your reason was: >as the line is interpreted right to left (c -> b -> a).
that is incorrect!
a is placed at higher memory and c at lower memory because stack always starts from higher memory. the compiler encounters a first and allocates memory for that first and decrements it's stack pointer(or data segment pointer; data segment is treated as stack). Then it encounters b and c respectively so they get successively lower addresses.

              |      |
              |      |
              |      |
0xffee     |      |
0xfff0      |  c  |
0xfff2      |  b  |
0xfff4      |_a_|    <- base pointer of stack (data segment); the stack's offset pointer is always                                    decremented, just before putting something on stack.

>  int a;
>  int b;
>  int c;
>should give something like
>  1008  c
>  1004  b
>  1000  a
>(a -> b -> c)
this is incorrect! the stack still look the same, i.e.:

              |      |
              |      |
              |      |
0xffee     |      |
0xfff0      |  c  |
0xfff2      |  b  |
0xfff4      |_a_|

the reason is the same, a is encountered first, followed by b and c. that is the order in which stack memory is allocated.

I verified this with turboc debugger. can you tell me what you get on the system you are using?
ofcourse what you are saying can be a fact if the compiler chooses to interpret the line:
int a,b,c; in reverse order c->b->a!
but that entirely depends on how the compiler is designed!
i think there should be a standard for this issue. that will make using pointers much more safer... i'm not aware if there already is.... please do respond with your views
Regards!
-logicTRANCE

NOTE: int is allocated only 2 bytes since i'm using turboc, it'll be 4 bytes on 32bit compiler... but everything else will remain same if i'm correct.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

A short article about problems I had with the new location API and permissions in Marshmallow
This is about my first experience with programming Arduino.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now