Unsigned char* and reinterpret_cast question - casting

This is a question for a University course that I only understand about half of.
#include <iostream>
using namespace std;
void printArray(double* array, int array_size) {
cout << "Array: ";
for (int i = 0; i < array_size; i++)
cout << array[i] << " ";
cout << endl;
}
int main() {
double d[] = {0, 0, 0, 0, 0};
unsigned char* uchar_ptr = reinterpret_cast<unsigned char*>(d);
printArray(d, 5);
for (int i = 0; i < 5; i++)
for (int j = 0; j < sizeof(double); j++)
uchar_ptr[i * sizeof(double) + j] = 1;
printArray(d, 5);
} ///:~
I understand that this program is creating an array of type double and printing its contents in the first function. Not sure what Main is doing.
My question is.
What exactly is unsigned char*
What exactly is 'reinterpret_cast<unsigned char*>(d)' doing
why is it 'double* array' and not just 'double array'
the question the text book asks is 'Why do you think each element was not set to the element 1?

Related

Accessing a dynamically created multi dimensional array with pointers arithmetic

I would like to understand how does it works to scan a dynamically allocated two-dimensional array using pointers arithmetics?
I can't figurate why in my example pointer arithmetic isn't returning the same results as using array indexing.
Here is my implementation:
#include <iostream>
using namespace std;
void init_matrix(int ** m, int size);
void print_matrix(int ** m, int size);
void print_matrix_pointers(int ** m, int size);
int main (){
srand (time(NULL));
int size = 3;
int ** dynamic_matrix = new int * [size];
for (int i = 0; i < 10; i++) {
dynamic_matrix[i] = new int [size];
}
init_matrix(dynamic_matrix, size);
cout << "Dynamic matrix accessed using square brackets ([i][j]): " << endl;
print_matrix(dynamic_matrix, size);
cout << "Dynamic matrix accessed using pointers arithmetics: " << endl;
print_matrix_pointers(dynamic_matrix, size);
return 0;
}
void init_matrix(int ** m, int size) {
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
m[i][j] = rand()%10;
}
}
}
void print_matrix(int ** m, int size){
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
cout << m[i][j] << " ";
}
cout << endl;
}
}
void print_matrix_pointers(int ** m, int size){
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
cout << *(*m + (i * size) + j) << " "; //
}
cout << endl;
}
cout << endl;
}
For instance if size was 3 I would get this output.
Dynamic matrix accessed using array indexing ([i][j]):
3 3 4
9 5 9
4 9 4
Dynamic matrix accessed using pointers arithmetics:
3 3 4
32735 9 5
9 32735 4
With *(*m + (i * size) + j) you treat m as a contiguous array of values, which it isn't. It's more like a jagged array. You need to treat it like the array of pointers it really is, like *(*(m + i) + j).
Two typos in your code:
int size = 3;
int ** dynamic_matrix = new int * [size];
for (int i = 0; i < 10; i++) {
dynamic_matrix[i] = new int [size];
}
size is 3 but you write 10 elements. That is undefined behavior.
Then you are advancing the pointer wrongly.
void print_matrix_pointers(int ** m, int size){
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
cout << *( *(m + i) + j) << " "; //
}
cout << endl;
}
cout << endl;
}
m points to an array of pointers to int. You have to increment m by i to get to the i-th row. Then you want to access the jth element of the array pointed to by m[i], hence you have to first dereference m+i then add j to get the address of jth element.

I am unable to get my code to get the stride of 7 to work properly C++

The question I am trying to solve is the following:
Write a function that traverses (and prints) the element of an array with stride =7. To do this the update part in the loop will be i= (i+7) % n, where n is the array size.
Would this function visit all elements of the array? Try different array sizes to check when it is impossible to traverse all elements.
The code that I wrote below doesn't print the correct values in the arry even if the value of i is correct.
Can anyone help, I would really appreciate it.
#include <fstream>
#include <stdlib.h>
using namespace std;
int* CreateArray(int n);
void StrideArray(int arr[], int n);
int main()
{
int* arr = new int[3];
arr = CreateArray(3);
cout << "The Elements In The Array Are: " << endl;
for (int i = 0; i < 3; i++)
{
cout << arr[i] << " ";
}
cout << endl;
StrideArray(arr, 3);
cout << "The Elements In The Array Stride 7 Are: " << endl;
for (int i = 0; i < 3; i++)
{
cout << arr[i] << " ";
}
delete[] arr;
return 0;
}
int* CreateArray(int n)
{
int* arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = (rand() % 100);
}
return arr;
}
void StrideArray(int arr[], int n)
{
int i = 0;
for (int j = 0; j < n; j++)
{
i = (i + 7) % n;
arr[j] = arr[i];
}
}
The problem is in StrideArray you read back the modified values of arr.
void StrideArray(int arr[], int n)
{
int i = 0;
int puffer=new int[n];
for (int j = 0; j < n; j++)
{
i = (i + 7) % n;
puffer[j] = arr[i];
}
for (int j = 0; j < n; j++){
puffer[j] = arr[j];
}
debete[] puffer;
}
Is a good way to write the function.
Also it visits all element only if n isn't dividable by 7. So if n is not 7,14,21,...
Also to use cout you have to #include <iostream>
Your StrideArray function needs fixing; you are iterating over j but using i to index, which remains constant; and you are reassigning value at one index to another where as you are supposed to print it:
void StrideArray(int arr[], int n)
{
int i = 0;
for (int j = 0; j < n; j=j+7)
{
cout << arr[j] << endl;
}
}
I modified the rest of your code for demo:
#include <iostream>
#include <stdlib.h>
using namespace std;
int* CreateArray(int n);
void StrideArray(int arr[], int n);
int main()
{
int* arr = new int[3];
arr = CreateArray(21);
cout << "The Elements In The Array Are: " << endl;
for (int i = 0; i < 21; i++)
{
cout << arr[i] << " ";
}
cout << endl;
StrideArray(arr, 21);
delete[] arr;
return 0;
}
int* CreateArray(int n)
{
int* arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = (rand() % 100);
}
return arr;
}

Why are the integers in the array negative after reversing the array and reversing back to the original array?

void reverseArray(int arrayLength, int sequence[]){
int temparr[arrayLength];
int *pointStart = sequence;
int *pointEnd = sequence + arrayLength - 1;
for(int i = 0; i < arrayLength; i++){
temparr[i] = *pointEnd - i;
}
for(int i = 0; i < arrayLength; i++){
sequence[i] = temparr[i];
}
}
void printArray(int arrayLength, int sequence[]){
for(int i = 0; i < arrayLength; i++, sequence++){
std::cout << *sequence << " ";
}
std::cout << "\n";
}
int main(int argc, char **argv) {
const int num = 50;
int arr[num];
for (int i = 0; i < num; i++){
arr[i] = i;
}
reverseArray(num, arr);
std::cout << "Printing reverse array...\n";
printArray(num, arr);
reverseArray(num, arr);
std::cout << "Printing reverse of the reverse array...\n";
printArray(num, arr);
ASSERT_EQ(0, arr[0]);
ASSERT_EQ(24, arr[24]);
ASSERT_EQ(49, arr[49]);
return 0;
}
I am able to reverse the array, but when I put the "reversed" array back into the function, it seems to be of negative elements. I am not sure where this happens... Anything will help! The unit testing isn't the problem, but it is a part of the code.
[1]: https://i.stack.imgur.com/MkfBC.png
You have a bug with this line:
temparr[i] = *pointEnd - i;
Here you are dereferencing the pointEnd pointer and subtracting i from the resulting integer.
What you meant to write is:
temparr[i] = *( pointEnd - i );
Here you are subtracting i from the pointEnd pointer, then dereferencing.
That being said, instead of doing confusing pointer arithmetic why not do something like this instead:
temparr[ i ] = sequence[ arrayLength - i ];

Trouble with segmentation faults in 3D array

I'm having trouble getting rid of the core segmentation fault on this code. It's creating a series of names in a 3-dimensional array with the dimensions row, col, and chars, where chars stores up to 5 letters of a name.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const int MAXSIZE = 11;
char*** names;
names = new char** [MAXSIZE];
cout << &names << " ";
for (int i = 0; i < MAXSIZE; ++i) {
names[i] = new char* [MAXSIZE];
cout << &names[i] << " ";
for (int j = 0; j < MAXSIZE; ++j) {
names[i][j] = new char [5];
cout << &names[i] << " " << i << j;
}
cout << endl;
}
I've inserted some debugging in there too. I see that it is able to finish assigning addresses, so I'm not sure what's going wrong. No other code is being done, even as I have deletes at the end that are all good.
Your code is ok, but remember that you can only store 4-symbol names in char[5] array.
Some modifications of your example
const int MAXSIZE = 11;
char*** func()
{
char*** names;
names = new char**[MAXSIZE];
for(int i = 0; i < MAXSIZE; ++i)
{
names[i] = new char*[MAXSIZE];
for(int j = 0; j < MAXSIZE; ++j)
{
names[i][j] = new char[5];
memset(names[i][j], 0, 5);
memcpy(names[i][j], "abcd", 4); // !!! only 4 symbols for name !!!
}
}
return names;
}
int main()
{
char ***names = func();
for(int i = 0;i < MAXSIZE;i++)
for(int j = 0;j < MAXSIZE;j++)
cout << names[i][j]<< endl;
// free memory
}

How to work with 3d arrays through pointers in C++

I'm facing some difficulties with pointers for 3D arrays in C++. I've a array of Q[3][N][N] which I want to pass to a function to print the values at [0][i][j] location (and also for [1][i][j] and [2][i][j]). How can I achieve this? Will it be more convenient to use Q[i][j][0] etc?
for 2D, the following piece of code works just fine when I give &Q[0][0] to the *var:
template <typename T>
void print2d(T *var, int I, int J){
cout << endl;
for (int j = 0; j < J; j++){
for (int i = 0; i < I; i++){
cout << setprecision(3) << setw(12) << *(var + (N*i + j));
}
cout << endl;
}
cout << endl;
}
I'm using the same approach to write a similar function for 3D which does not write out the correct values:
Can anybody let me know the correct way to point to the correct address of Q[i][j][1]. In input argument, I'm giving the address of Q[0][0][0]. Should I use different addresses (such as Q[i][j][1]) if I want to write out for that particular value of k?
template <typename T>
void print3d(T *var, int I, int J, int K){
cout << endl;
for (int j = 0; j < J; j++){
for (int i = 0; i < I; i++){
cout << setprecision(3) << setw(12) << *(var + I*J*i + I*j + K);
}
cout << endl;
}
cout << endl;
}
Sample example, N must be const.
But consider using vector.
#include <stdio.h>
#include <iostream>
using namespace std;
const int N = 5;
void func2(int* tab, int A, int B, int C)
{
printf("%d\n", tab[N*N*A + N*B + C] );
}
void func(int tab[3][N][N])
{
for (int i = 0; i < 3; ++i)
for (int j = 0; j < N; ++j, printf("\n"))
for (int k = 0; k < N; ++k)
{
printf("%d ", tab[i][j][k]);
}
}
int main()
{
int tab[3][N][N];
int p = 0;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < N; ++j)
for (int k = 0; k < N; ++k)
{
tab[i][j][k] = p++;
}
func(tab);
printf("\n");
func2((int*)tab, 1, 1, 3);
}
I agree with Adam's answer but cant comment, need more points there.
1) Arrays are not pointers. Multidimensional arrays cannot be passed via a pointer, needs to have all but one dimension constant. Here is an answer to help understand.
Cannot cast array to pointer
How do I pass a reference to a two-dimensional array to a function?
http://www.cplusplus.com/forum/articles/17108/
You might want to try vectors from STL instead.
2) Templates are compiled only when there is an instance of it used, that is why its declaration and usage is generally put in one file.
Template Compilation