Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Mar 1st, 2006, 9:10 PM   #1
Mcoy
Newbie
 
Mcoy's Avatar
 
Join Date: Mar 2006
Posts: 20
Rep Power: 0 Mcoy is on a distinguished road
Getting values of (non-dynamic) arrays...

Is a statement like:
a = bob[fred[2]];
valide in c++?(Bob and Fred are two different arrays.)

I know that something like
a = bob[bob[2]];
is valid but a program of mine crashes when I combine two different arrays like I've shown.
Mcoy is offline   Reply With Quote
Old Mar 1st, 2006, 9:59 PM   #2
Jimbo
Battle Programmer
 
Jimbo's Avatar
 
Join Date: Feb 2006
Location: Bellevue, WA, USA
Posts: 751
Rep Power: 3 Jimbo is on a distinguished road
if fred[2] is a valid index of bob[], then it should work.
#include <iostream>

int main()
{
	int bob[] = {2, 3, 4, 5, 6};
	int fred[] = {0, -1, 4, 17, 44};
	std::cout << bob[fred[2]] << std::endl; // outputs 6
	return 0;
}
Jimbo is offline   Reply With Quote
Old Mar 2nd, 2006, 6:42 PM   #3
Mcoy
Newbie
 
Mcoy's Avatar
 
Join Date: Mar 2006
Posts: 20
Rep Power: 0 Mcoy is on a distinguished road
Thanks, I guess I could have figured it out by trying code like that, but I wanted to go to bed by the time I came to that problem :o .
'fred[2]' was indeed a valid index of 'bob[]', but it still crashed.
For some reason filling fred with zero's fixed the problem.
Mcoy is offline   Reply With Quote
Old Mar 2nd, 2006, 7:25 PM   #4
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
If 'fred [2]' isn't initialized with a known value, it's accidental value might very easily represent an index not within the bounds of Bob (or any other array). Seg fault. Barf in cuffs. All that bad chit.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 1:55 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC