2

I have the following two dimensional array:

#define ROW 100
#define LINE 50

int a[ROW][LINE];

but how to get the sizeof array for the last 45 rows, for example a[55][0] to a[99][99]?

can we do something like sizeof(&a[55])?

4
  • The 45 last rows would be a[55][0] to a[ROW - 1][LINE - 1]. Commented Jun 24, 2013 at 20:24
  • As Hunter said, but you generally want to avoid fixed sized arrays like that, because you are hardcoding the buffer size and at some point you will want to store more... Commented Jun 24, 2013 at 20:25
  • can we use pointer to get the size, this can avoid the fixed size arrays Commented Jun 24, 2013 at 20:27
  • Using the pointer to get the size doesn't really make sense -- sizeof(int *) is fixed (generally 4 or 8 bytes, depending on arch, but this is not guaranteed), regardless of how much memory is allocated at the place your pointer is pointing to. Commented Jun 24, 2013 at 20:30

2 Answers 2

7

sizeof of an array is guaranteed to be equal to the sizeof of a single element multiplied by the number of elements. So, if you want to know how much memory is occupied by a specific number of rows, just calculate the number of elements and multiply by element size. 45 rows would require

45 * LINE * sizeof a[0][0]

Or, alternatively

45 * sizeof a[0]

It doesn't really matter whether these are last 45 rows. All rows are the same.

Sign up to request clarification or add additional context in comments.

Comments

1

If you want just the last lines, from line 55 and forward, how about

(ROW - 55) * LINE * sizeof(int)

If you just want a generic N number of lines, then how about

N * LINE * sizeof(int)

5 Comments

@user2131316 As soon as an array decays into a pointer, all you have is the pointer, and pointers don't have information (like size) about the data it points to.
@kotlomoy You're correct, I always mix the expression and type sizeof operators. That's why I usually always use the variant with parentheses.
@kotlomoy: The syntax is sizeof expr or sizeof ( type-name ). The expr can be a parenthesized expression. It's the same in C89/C90, C99, and C11.
@KeithThompson My comment was for error in this answer. Error is fixed now. And I agree with Joachim - the best way is to always use parentheses. Thansk for explanation though - I wasn't sure about C99/C11 syntax. (Yes, I work in Visual Studio)
@kotlomoy: Personally, I usually apply sizeof to expressions (specifically object names), not to types, and I usually don't add parentheses unless it's necessary. Parentheses make it look too much like a function call, when in fact it's a unary operator. But as with most style questions, there's no One True Way.

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.