#### Archived

This topic is now archived and is closed to further replies.

# Pointers and Arrays

This topic is 5864 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am currently taking a C++ class at the Uni. :-), I tend not to pay attention because it is being taught at a first grade level. Although, one thing did catch my attention. The other day the teacher was talking about arrays and pointers, and he stated it is best to use this method when iteratating through an array using pointers: Manually incrementing the pointers and the array =============================== int array[100]; int ptr_array = &array[0]; for(int i=0; i<100; i++, ptr_array++) ===================================== Although, I usualy would just do: for(int i=0; i<100; i++) *ptr_array++; ====================== The teacher says my method would create extra overhead time. Furthermore, I do not pay much attention to my teacher because a few days ago he chose to pass an array by VALUE. A very large array, and showed the students that u don''t need a data type in front of main and other strange things. Good thing everything you want to know is in a book! ----------------------------- "There are ones that say they can and there are those who actually do." "...u can not learn programming in a class, you have to learn it on your own."

##### Share on other sites
quote:
The teacher says my method would create extra overhead time.

Both of you suck, if you''re trying to figure who''s the better "optimized" programmer.
int array[100];int *ptr = &array, *end = &array[99];for(; ptr != end; ++ptr)  // loop body here

That''s basically how iterators work.

quote:
Furthermore, I do not pay much attention to my teacher because a few days ago he chose to pass an array by VALUE.

Arrays are always passed by reference in C++. Always.

quote:
...[he] showed the students that u don''t need a data type in front of main and other strange things.

What do you mean data type "in front"? If main doesn''t have a return type (like any other function), it will fail to compile. If he specified return type void for main, or indeed any return type other than int, then he hasn''t caught up with the standard.

If, however, he declared it as int main(void), then he''s perfectly right.

Moral? Pay attention to your teacher, twerp.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!

##### Share on other sites
He was probably pointing out that doing a loop via pointer arithmetic is faster than array indexing, as in:

  for (i=0; i<100; i++, ptr++) // use *ptris faster than:for (i=0; i<100; i++) // use array[i]

which is usually true, depending on the optimization. Your two examples will generate virtually identical code, assuming a non-brain-dead optimizer:

  for (i=0; i<100; i++, ptr++) // use *ptrfor (i=0; i<100; i++) // use *ptr++

Also, I believe your prof is correct on the two other points. Routines without a declared return are assumed to return int, as is the main procedure. And passing an array via a parameter will not pass it by value; arrays cannot be passed by value.

I''d suggest not discarding everything your prof tells you out of hand. If you believe he has stated something incorrect.y, look it up to double check. Remember, there''s always something to learn.

##### Share on other sites
"*ptr_array++;" increments the value stored in the first element of the array, NOT the pointer to the array.

lookup pointer dereferencing....

To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.

##### Share on other sites
Actually I went home and wrote a program with no data type in front of Main() and it compiled and ran,but I did get a warning.
Using MSVC 6.0. Doesn't the copy constructor get called when I am passing an array in as the parameters. Furthermore, good point OldGuy, there is always more to learn! Also, I expected better from you Oluseyi, since you are a moderator. Oh well, I would of used a vector anyway. Try it out for yourself.
===================================

#include < iostream.h>
main()
{
cout << " Oluseyi sucks donkey balls.\n";
}
===================================

-----------------------------
"There are ones that say they can and there are those who actually do."

"...u can not learn programming in a class, you have to learn it on your own."

Edited by - cMADsc on February 1, 2002 2:35:22 PM

Edited by - cMADsc on February 1, 2002 2:35:57 PM

##### Share on other sites
no data type, is assumed "signed int", period.

no arrays do not get copied, arrays are "basically" constant pointers.

To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.

##### Share on other sites
sorry jenova but you''re about "*ptr_array++;" It DOES increment the pointer increase, not the value at the pointer.

int a[] = {1, 5, 8, 9};
int *p = a;
cout << *(p++) << endl;
cout << *p++ << endl;

What''s the output?

1
5

Look up order of operations...

##### Share on other sites
I think *end = &array[99] is wrong. The "end" iterator should not point to the last element, but just after. So (&array[99])+1

don''t leave off the return type on int functions, it is like swearing at a tea party. Plus it only works in C, though C++ compilers might let it pass.

Use ++i instead of i++. For built in types such as ints or pointers both have the same performance. For iterators and other types the i++ version requires an extra temporary. Plus it is more appealing to the eye, I switched over before I heard about the performance issue.

##### Share on other sites
quote:
no data type, is assumed "signed int", period.

Not in C++ it ain''t.

##### Share on other sites
Yes, knowing the precedence order of operators is important (or, if you are like me, with a bad memory, dogearing the page in the manual). The first time I saw this code like this:

  char tobuf[100], frbuf[100], *t, *f;strcpy(frbuf, "Hello, World");t = tobuf;f = frbuf;while (*f) *t++ = *f++;*t = ''\0'';

I almost had a stroke trying to figure it out the first time. The key is knowing (or looking up) the precedence of the operators. In *f++, ++ has a higher precedence than *, which means it is applied first. However, it is a postfix operator, so the effects take place later (another way to think about it is that ++ increments the variable but returns the previous value). Then, the indirection operator gets the value pointed to by ''f''. The effect is that *f++ returns the value pointed to by f, THEN increments f to the next address.

Which comes to another point. The above is commonly accepted usage, and you should get used to it. But, you can produce some very odd-looking expressions in C++. Sometimes clarity is better than cleverness, so a rule of thumb is to try to avoid overly complex code unless absolutely necessary. I always get a chuckle when I break this rule, and come back several weeks/months later to try to figure out what my code is actually doing. I cuss out the damned programmer who that pile of garbage, and then my ears burn red...

##### Share on other sites
quote:
Also, I expected better from you Oluseyi, since you are a moderator.

Here we go again...

Listen, youngun''. You post with attitude as if to say "I''m better than everyone in my class, and my teacher sucks!" I am merely sitting your juvenile ass where it belongs, and giving you a lecture in respect. If you don''t fucking know what you''re talking about, STFU.

"You would have used a vector anyway..." but you still use the old iostream header? If you want to get anal on code, I''ll kill you because I have more experience, more ability and more knowledge than you do.

The moral? Respect your elders. And RTFM.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!

##### Share on other sites
quote:
Original post by Anonymous Poster
I think *end = &array[99] is wrong. The "end" iterator should not point to the last element, but just after. So (&array[99])+1

Good point.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!

##### Share on other sites
often teachers give "inaccurate" info to help explain things or build foundation. just because ur teacher isnt explaining things that might be complex to newbies, that doesnt mean he doesnt plan to, and it doesnt mean he doesnt know what hes doing, he is *Teaching*, not writting a reference book.

##### Share on other sites
Good point EvilCrap, sometimes I do tend to get cocky. Although, most of it is from frustation, I hate seeing my fellow peers graduate and not have a job waiting because they really cannot do anything. This was not a judge in character, some clarity was just needed. Oluseyi, yes I had used the old header, but at school the students are taught to program in Telnet and it has a weird compiler installed that will make u alter you code. Also, stop action like a Bia Bia. If you have something to say, drop knowledge, enough with the bitching. Next time I'm in NC interviewing at RTP, come show some code. To be the best you have to beat the best. Arguing defeats my purpose, I came to seek knowledge. Thx for the SGI link.

-----------------------------
"There are ones that say they can and there are those who actually do."

"...u can not learn programming in a class, you have to learn it on your own."

Edited by - cMADsc on February 2, 2002 1:48:23 AM

##### Share on other sites
quote:
Original post by DrPizza
Not in C++ it ain''t.

It isn''t in C either. That ''feature'' was removed from the standards a decent while ago.

##### Share on other sites
quote:
Doesn''t the copy constructor get called when I am passing an
array in as the parameters

What copy constructor? It''s not an object.

My compiler still assumes signed int for any function/method I don''t specific it for... MSCV6.

  DWORD* p = 0xA0000000;const int n=16000;for(int i=n; i>=0; ++p)[i]p = 0xFFFFFFFF;

Modern CPUs may execute both at the same speed (indexing and dereferencing)... hard to say. Might be a tick difference.

Incremeneting two varibles per loop is bad. Indexing would be faster than that.

Odds are _really good it wouldn''t matter.

##### Share on other sites
Sorry about that M.K.H, I know that but I must of been thinking about something else. Could you elaborate about incrementing 2 variables in a loop? To Oluesyi, may bad, I should of never stepped down to your level. Now if I need help on Linux ,(or hash table) you probably will not help. :-(

##### Share on other sites
quote:
for(int i=0; i<100; i++, ptr_array++)

^^Two variables ++, per loop. As pointed out above, you only need to inc one.

##### Share on other sites
quote:
Also, stop action like a Bia Bia. If you have something to say, drop knowledge, enough with the bitching. Next time I''m in NC interviewing at RTP, come show some code. To be the best you have to beat the best.

I didn''t fully understand this because of your contorted English and use of acronyms i''ve never heard of, but from what i can tell you are implying that you are a better coder than Oluseyi. Which i highly doubt. Even though Oluseyi does have a short temper and little patience, he does know what he is talking about and can be very helpful if approached with manners and humility. Of which you have neither.

"There are ones that say they can and there are those who actually do."

Which are you, i wonder?

##### Share on other sites
quote:
for(int i=0; i<100; i++, ptr_array++)

^^Two variables ++, per loop. As pointed out above, you only need to inc one.

And if he''s going over crap like that, I can only assume that C isn''t a prerequiste?

##### Share on other sites
Sprial I did not mean in any way I was better them him. I mean for him to bring some code for me to look at and learn from. :-) That is what I mean "to be the best you have to beat the best". I hope you see. I am trying to get where he is so called at. Furthmore M.K.H. that is what I was thinking about in using just needing one to increment, but he said it was quicker using to two variables. Also, C is not a prereq, freshmans are taught java as the first langauge. Although, I did speak with the dept and told them it will be difficult from the freshman to learn java freshman year and then take C probably sophmore year. C is not required but is offered. I was thinking C->C++->Java.That is just my opinion. I learned pascal my first year, any thoughts about that.

-----------------------------
"There are ones that say they can and there are those who actually do."

"...u can not learn programming in a class, you have to learn it on your own."

Edited by - cMADsc on February 2, 2002 2:35:26 AM

##### Share on other sites
quote:
I mean for him to bring some code for me to look at and learn from.

I posted code in the first reply. Someone corrected my assignment of end, but the logic is tight and the code is efficient because a.) it increments only one variable; b.) it doesn''t evaluate the end condition on every iteration; and c.) it uses preincrmentation rather than post, which is faster and more efficient unless the compiler can detect that the copy is unnecessary and optimize that out.

Any further questions? I don''t need to prove myself, and I don''t generally care what people think. You don''t know me, and you likely never will. I''m incredibly blunt and thick-skinned too, so saying I''m acting like a "bia bia" doesn''t bother me. I''m not here to play nice; I''m here to answer questions, and I''m a moderator to regulate bitch-ass motherfuckers.

Was born to dictate, never follow orders,
Fucker, this is big ''Seyi. I...
Will. Not. Lose.

Ever.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!