c++: what is int[3] in sizeof(int[3]) - c++

This is my example:
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int ar[][3] = {1, 2, 3, 4, 5, 6, 7};
//cout << int[3]<<endl; // error C2062: type 'int' unexpected.
cout << "sizeof(ar) / sizeof(int[3]) "<< sizeof(ar) / sizeof(int[3]) << endl;;
system("pause");
return 0;
}
It is from a book, though no explanation was given. What is int[3] here and why it works only as an argument of sizeof in this case?

int[3] is a type declaration that represents an array of three integers.
Your commented code gives an error because you can't use a type as a variable.

sizeof(int[3]) is the size, in bytes, of an array of three integers. sizeof isn't an actual function that gets called while your program is running - it is resolved at compile time. sizeof(ar) / sizeof(int[3]) will give you the number of rows in your array, since each row is 3 integers long (you declared it as int ar[][3]).

The declaration
int ar[][3] = {1, 2, 3, 4, 5, 6, 7};
is for an array of triplets of integers - it is a 2D array.
The sizeof expression
cout << "sizeof(ar) / sizeof(int[3]) "<< sizeof(ar) / sizeof(int[3]) << endl;
prints the number of full triplets that you get. The last integer, 7, will not fall into any triplet. You should see 2 printed. ar[0] will contain {1, 2, 3} and ar[1] will contain {4, 5, 6}.

Related

converting char array to int using c++

Can anyone explain me how this code results 16843009? How it works?
As I saw in my tests, (int *)&x results 0x61ff1b and as I know that is the address of the first element in the array. and how the result of *(int *)&x is 16843009? Thanks.
#include <iostream>
using namespace std;
int main()
{
char x[5] = {1, 1, 1, 1, 1};
cout << *(int *)&x;
return 0;;
}
If we write 16843009 as binary we get 1000000010000000100000001. Padding that with extra zeros we get: 00000001000000010000000100000001. Every 8 bits (which is a char) has a value of 00000001, which is 1.
&x is a pointer to an array of char (Specifically a char(*)[5]). This is reinterpreted as a pointer to int. On your system, int is probably 4 bytes, and all four of those bytes are seperately set to 1, which means you get an int where every 8 bits are set to 1.

Garbage value getting displayed on printing 2d array using row order

I am using gcc compiler on ubuntu 16 , when I am printing value garbage value is getting displayed
#include <bits/stdc++.h>
int Arrayprint(int r, int l, unsigned int* q)
{
r = 3;
l = 4;
for (int i = 0; i < r; i++) {
for (int j = 0; j < l; j++) {
cout << *(q + sizeof(unsigned int) * (i * l + j)); //Garbage getting diplay
cout << *(q + i + j); //this working
cout << "\t";
}
}
cout << "size of unsigned int : " << sizeof(unsigned int); //4
cout << "size of int : " << sizeof(int); //4
}
int main()
{
unsigned int image[R][L] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
unsigned int* q = (unsigned int*)image;
Arrayprint(R, L, q);
}
From what I can tell, you understand at a low level that the address of the ith element of an array of T is base + sizeof(T) * i. That's correct, and it's good that you know that.
However, C and C++ handle this for you already. When you say q + i or q[i], it's actually compiling that into q + sizeof(T)*i anyway (with the latter also dereferencing the result).
So when you say q[sizeof(int)*i], that's actually compiling into *(q + sizeof(int)*sizeof(int)*i), which is clearly not what you wanted.
Thus, the index in the array you actually access is off by a factor of sizeof(int) and results in an out of bounds error, which is where your strange numbers are coming from.
I am using gcc compiler on ubuntu 16 , when I am printing value
garbage value is getting displayed
Instead of trying to fix what's broken in your raw array arimethics, consider using the standard containers:
#include <iostream>
#include <array>
constexpr size_t R = 3;
constexpr size_t L = 4;
using image_t = std::array<std::array<unsigned int, L>, R>;
void Arrayprint(const image_t& q) {
// range based for loops for convenience
for(auto& row : q) { // get references to each row
for(unsigned int colval : row) { // get the column values
std::cout << colval << "\t"; // print the values
}
std::cout << "\n";
}
}
int main() {
image_t image = {{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}};
Arrayprint(image);
}
Output:
1 2 3 4
5 6 7 8
9 10 11 12

Char Point Memory Allocation to reference address of C++ String?

I would like to convert an array of Integers
2, 3, 4, 8
5, 7, 9, 12
1, 0, 6, 10
to a string with the entries of that matrix appended in clockwise order
“2, 3, 4, 8, 12, 10, 6, 0, 1, 5, 7, 9”.
I have to keep declaration of int * Matrix and char * OutBuffer the way they are
int main()
{
int matrixArray[rowCount][columnCount] =
{ {2, 3, 4, 8},
{5, 7, 9, 12},
{1, 0, 6, 10}};
int * matrix;
string prebuffer;
char * outBuffer;
outBuffer = new (nothrow) char[24];
matrix = &matrixArray[0][0];
BuildStringFromMatrix(matrix, rowCount, columnCount, outBuffer);
}
I declare and address all my pointers before passing them in. However, I am not sure if I am going about allocating memory for the outBuffer to store the characters of prebuffer correctly?
void BuildStringFromMatrix(int* Matrix, int NumRows, int NumColumns, char * OutBuffer)
{
string prebuffer;
bool stringLeft = true;
int i = 0;
while (stringLeft)
{
int clockwiseDir[12] = { 1,1,1,4,1,1,0,4,-4,-1,-1,-1 };
prebuffer = to_string(Matrix[i]) + ", ";
OutBuffer = new char [prebuffer.length() + 1];
cout << prebuffer;
i += clockwiseDir[i];
if (i == 6)
{
prebuffer = to_string(Matrix[i]) + " ";
cout << prebuffer;
stringLeft = false;
}
}
}
**When I do not implement OutBuffer I have no trouble accessing and printing the matrix in clockwise format
But I how would I go about using OutBuffer to reference and print prebuffers contents??
I need numbers to display not unprintable symbols on the ASCII table
Thanks in advance :)
**
Firstly, in your loop under BuildStringFromMatrix function you are not using your i value anywhere.
Second, matrix = matrixArray should do fine.

Memory Dump error on runtime

What is the problem in this code ? It shows memory dump error in runtime
#include<iostream>
using namespace std ;
int main()
{
int A[3][4] = {{3, 1, 8, 11}, {4, 12, 9, 10}, {7, 5, 2, 6}};
int **p = A;
P[1][2] = 99;
cout<<A[1][2] ;
}
Change your int **p = A[0][0] to int *p = &A[0][0]. In the next line, write the following *p = *((int*)p + 1 * NUM_OF_COLUMNS + 2) = 99;, where NUM_OF_COLUMNS is the number 4, instead of the P[1][2] = 99;. Correct the spelling of main as well as uppercase/lowercase of variables. Also add a return 0; at the end since you have an int main() and not a void.
you seem new to c++ or programming with a question like this one don't feel bad because pointers can be tricky and if you don't know you don't know. I am pretty sure this will help you. Remember to pick the best answer :).
#include <iostream>
using namespace std;
int main() {
int A[3][4] = { { 3, 1, 8, 11 }, { 4, 12, 9, 10 }, { 7, 5, 2, 6 } };
cout << "Before pointer change A[1][2] = " << A[1][2] << endl;
int *p; //Set pointer
p = &A[1][2]; //Set memory address to pointer don't forget '&'
*p = 99; //Change integer
cout << "After pointer change A[1][2] = " << A[1][2] << endl;
return 0; // you need a 'return 0;' because your main is int
}

Calculating both weighted and unweighted statistics with the same boost::accumulator_set?

With Boost's accumulators I can easily calculate statistical quantities for
weighted or unweighted input sets. I wonder if it is possible to mix weighted
and unweighted quantities inside the same accumulator. Looking at the
docs it doesn't seem that way.
This compiles fine but produces another result than I would have liked:
using namespace boost::accumulators;
const double a[] = {1, 1, 1, 1, 1, 2, 2, 2, 2};
const double w[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
accumulator_set<double, features<tag::sum, tag::weighted_sum>, double> stats;
for (size_t i=0; i<9; ++i)
stats(a[i], weight = w[i]);
std::cout << sum(stats) <<" "<< weighted_sum(stats) << std::endl;
// outputs "75 75" instead of "13 75"
Also, with a third template parameter to accumulator_set I always seems to
get weighted quantities, even when using an "unweighted" feature and extractor:
accumulator_set<double, features<tag::sum>, double> stats;
for (size_t i=0; i<9; ++i)
stats(a[i], weight = w[i]);
std::cout << sum(stats) << std::endl;
// outputs "75" instead of 13
Do I always have to use two different accumulators if I want to calculate both
weighted and unweighted quantities?
EDIT
I just use sum as an example, in reality I am interested in multiple, more complicated quantities.
It does say in the documentation that
When you specify a weight, all the
accumulators in the set are replaced
with their weighted equivalents.
There are probably better ways to do it but you can try something like this (basically swapping the meaning of the value with that of the weight):
accumulator_set< double, stats< tag::sum, tag::sum_of_weights >, double > acc;
const double a[] = {1, 1, 1, 1, 1, 2, 2, 2, 2};
const double w[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
for( int i = 0; i < sizeof( a ) / sizeof( a[ 0 ] ); i++ )
acc( w[ i ], weight = a[ i ] );
std::cout << extract_result< tag::sum >( acc ) << std::endl; // weighted sum, prints 75
std::cout << extract_result< tag::sum_of_weights >( acc ) << std::endl; // sum, prints 13