2

I primarily program in Java but I am taking a graphics course for which I need to use C++. I am trying to create an array of objects in order to loop through them and draw them to the screen, but I can't for the life of me figure out how to create this array. I have code now which does not produce any compiler errors, but it doesn't seem to work correctly either. The following code is at the top of my Main.cpp class:

Platform ground("wallstone.tga", 40, 16, 4, 144);
Platform platform1("wallstone.tga", 10, 16, 4, 20);
Platform platforms[2] = {ground, platform1}

When I try: fprintf(stdout, "Size of platforms array: %d", sizeof(platforms)/sizeof(Platform)); it prints out 0.0.

I've tried several ways of creating this array and they all seem to produce errors or that same output of 0.0, so I'm not sure what's going on. If any more of my code is necessary I will certainly be willing to post it. Of course, if there is a better way of approaching this I am grateful. Thanks!

7
  • 3
    I'm curious how the %d format specifier resulted in 0.0... Commented Mar 9, 2013 at 18:58
  • 1
    Side note : Why fprintf ? You can use printf. Commented Mar 9, 2013 at 18:58
  • Also, the correct format specifier for size_t is %uz, and anyways in C++ you should use std::cout instead of printf(). Commented Mar 9, 2013 at 18:59
  • I typed the code from memory and made a few mistakes, meant %f. And fprintf is just the one I know haha. Commented Mar 9, 2013 at 19:02
  • If you're not married to arrays, you might find the collection classes in the STL, like vector, easier to deal with. Just sayin'. Commented Mar 9, 2013 at 19:02

1 Answer 1

3

It looks like you are doing everything right. My only guess is that size_t on your platform is larger than int, so providing a correct format specifier (%z instead of %d) may fix the problem:

fprintf(stdout, "Size of platforms array: %z", sizeof(platforms)/sizeof(Platform));
Sign up to request clarification or add additional context in comments.

3 Comments

alternately, cast the expression to int: (int)( sizeof(platforms)/sizeof(platforms[0]) )
That was precisely the problem, thanks so much! My function that loops through the array still isn't working (I was hoping the size issue was the problem), but I'll keep working on it. I appreciate it.
@H2CO3 You're right, the format for size_t is z. I didn't realize that size_t has its own format now :) Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.