Sorry for the newbie question, I am still learning.
Let's say that I have matrix[x][y]
Using sizeof(matrix)
will return me the whole size of the array.
Using sizeof(matrix[a])
will return me the size of a certain row.
Using sizeof(matrix[a][b])
will return me the size of what is located in [a][b].
Is there a way to just find the size of a column? If there is not, why? Am I overlooking something? Thanks for your time.
EDIT: Thanks for the help, if someone else is looking for the answer the user "nnn" wrote the following:
For the number of elements in a column:
sizeof(matrix) / sizeof(matrix[a])
For the size in bytes occupied by a column:
sizeof(matrix) / sizeof(matrix[a]) * sizeof(matrix[a][b])
Also "Weather Vane" explains how sizeof works:
sizeof
finds the extent of contiguous byte usage in memory, so it can't be used directly to find the amount of memory used by each column. The array, a row, or an element: yes. A column: no
We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
The sizeof() operator returns pointer size instead of array size. The 'sizeof' operator returns size of a pointer, not of an array, when the array was passed by value to a function. In this code, the A object is an array and the sizeof(A) expression will return value 100. The B object is simply a pointer.
You can use the sizeof operator to determine the size that a data type represents. For example: sizeof(int); The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding.
sizeof(type) gives you the number of bytes of the type you pass. Now if you pass array then the compiler knows that this is an array and number of elements in it and it just multiplies that many elements with the respective data-type size value.
For the number of elements in a column, divide matrix size by row size:
sizeof(matrix) / sizeof(matrix[a])
For the size in bytes occupied by a column (the actual answer for the question), multiply number of elements (previous expression) by element size:
sizeof(matrix) / sizeof(matrix[a]) * sizeof(matrix[a][b])
Even if this can't be achieved by using a single sizeof
operator, the sizeof
is evaluated at compile time, and usually the compiler will substitute these arithmetic operations with the actual result, so there will be no runtime performance degradation caused by this.
Also, the usage of a
and b
in the expression above can be replaced by 0
, i.e. matrix[0]
and matrix[0][0]
, because all the elements have the same size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With