Arrays and pointers together acting weirdly [duplicate] - c++

This question already has answers here:
Why do you have to specify a type for pointers?
(3 answers)
Pointer Arithmetic [closed]
(7 answers)
Closed 13 days ago.
So, I've been learning C++ recently and I have been trying to grapple with pointers and that sort of memory management. This is a simple program I wrote that prints out an array to the cout:
#include <iostream>
int main() {
int x[10] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34};
for(int i = 0; i < 10; i++) {
std::cout << *(x + i) << ", ";
}
}
And this works fine- however I'm a bit confused why line 7 (std::cout << *(x + i) << ", ";) isn't, instead, std::cout << *(x + i * sizeof(int)) << ", ";. Since "i" only increments by one, and the array is a list of multi-bit integers (traditionally 32 bit), shouldn't I have to increment it by the size of one of these integers to get the next int value?
Apologies if I'm not properly understanding how this all works, but any response is appreciated! Thank you!

Related

c++ vector [-2] index returns weird value [duplicate]

This question already has answers here:
Accessing negative index of vector via operator[] and .at()
(2 answers)
Closed 1 year ago.
I'm new to c++ and just learned about vectors. I'm coming from Python, so of course I checked if I could use negative indexing in c++, which did not seem to work.
While trying to check if it works, I met a very weird behaviour for negative indexes in different environments.
Using negative indexes with the .at() function raises an error but not when using [] brackets.
Are these values contents of previous memory locations, or what do they represent? Is this what's called undefined behaviour?
Source:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {3, 6, 9, 12, 15};
std::cout << "Length: " << numbers.size() << "\n";
for (int i = 4; i > -5; i--) {
std::cout << "Pos " << i << ": " << numbers[i] << "\n";
}
}
Output:
Length: 5
Pos 4: 15
Pos 3: 12
Pos 2: 9
Pos 1: 6
Pos 0: 3
Pos -1: 0 // other env: 201392090
Pos -2: 33 // other env: 475047512
Pos -3: 0
Pos -4: 0
Are these values contents of previous memory locations, or what do they represent? Is this what's called undefined behaviour?
No, it's not actually accessing a memory location prior to the beginning of the backing array, but one past the end:
If you use numbers [index], the compiler interprets this as numbers.operator[](index), i.e. the member function operator[]() is used. This function takes a parameter of type size_t which is an unsigned integer. The parameter -1 is implicitly converted to a unsigned integer yields a very large number and this number is out of range of values the contract of std::vector covers. Read or write access to such an element is undefined behaviour. at in contrast to operator[]() does compare the parameter to the vector size guaranteeing an exception in this scenario, but with operator[] there's no such "safety net".
You can use negative indexing in C++, not just on a container that starts at index 0.
However, you can have an iterator into the middle of a vector and index from that.
std::vector<int> numbers = {3, 6, 9, 12, 15};
std::vector<int>::iterator it = numbers.begin() + 3;
std::cout << it[-2];

content of a vector appears to be empty but a value is assigned to it (C++) [duplicate]

This question already has answers here:
Accessing an array out of bounds gives no error, why?
(18 answers)
uint8_t can't be printed with cout
(8 answers)
Closed 1 year ago.
this is probably a really basic C++ question but I'm very new to C++ so your patience and help is appreciated.
I'm not quite sure why the following code is unable to print out the content of the matrix. I should mention that the variable K is the integer 3.
std::vector<uint8_t> enc_matrix;
for(size_t i = 0; i != K; ++i) {
enc_matrix[i*(K+1)] = 1;
cout << "enc_matrix: " << enc_matrix[i*(K+1)] << endl;
// cout << enc_matrix.at(i*(K+1)) //doesn't show anything either
cout << "i: " << i*(K+1) << endl;
}
For whatever reason nothing gets printed for enc_matrix[i*(K+1)] but the result of i*(K+1) does get printed. Below is what gets printed:
enc_matrx:
i: 0
enc_matrx:
i: 4
enc_matrx:
i: 8
I'm not sure if it has anything to do with the type of the matrix so I've included the additional info below:
typeid(enc_matrix[0]).name() => h and
typeid(enc_matrix).name() => St6vectorIhSaIhEE
Why is it that enc_matrix doesn't get printed? I am expecting to see 1 assigned to it when i equals to 0, 4 and 8. Thank you.

how does the std::sort() function in C++ work? [duplicate]

This question already has an answer here:
C++ Sort Error "No instance of overloaded function.."
(1 answer)
Closed 1 year ago.
I'm using Programming Principles and Practice Using C++ as my guide and reference to learn programming and c++. In chapter 4.6.4 the book showed this snippet of code.
int main()
{
vector<string> words;
for (string temp; cin >> temp; ) // read whitespace-separated words
words.push_back(temp); // put into vector
cout << "Number of words: " << words.size() << '\n';
sort(words); // sort the words
for (int i = 0; i < words.size(); ++i)
{
if (i == 0 || words[i-1] != words[i]) // is this a new word?
cout << words[i] << "\n";
}
}
in this example the sort function shows error, so I did a bit of searching up on google to get a better understanding of the sort function, and from what I understood the first perimeter of the sort function takes in the array or vector it is going to sort and the second variable tells the sort function where to sort it up to.
int main()
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
sort(arr, arr[5]);
}
form what I understand the code snippet should sort up to the 6 element of the array, but the compiler shows me an error. So I tried different ways of trying to get it to work. However, only the way shown in geek for geek forum work.
int main()
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
/*Here we take two parameters, the beginning of the
array and the length n upto which we want the array to
be sorted*/
sort(arr, arr + n);
cout << "\nArray after sorting using "
"default sort is : \n";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}
could someone explain how it really work
The first example is working in C++20, if sort is from the ranges namespace. Is it mentioned in the book/tutorial your are reading?
sort(arr, arr[5]); in your terms, arr[5] is not "where", it's an array element, i.e. "what". "Where" is the address &arr[5] or &arr[n]. You could use std::begin(arr) and std::end(arr) instead of arr and &arr[n].
How std::sort work is very well explained with examples on std::sort.

C++, error when finding length of an array, only when using SEPARATE FUNCTION [duplicate]

This question already has answers here:
What is array to pointer decay?
(11 answers)
C sizeof a passed array [duplicate]
(7 answers)
Length of array in function argument
(9 answers)
Closed 5 years ago.
when I'm finding the length of an array, it keeps returning 2 if it is used in a seperate function. If i find the length in the main function however, it finds the length properly. If anyone can help, thank you so much. I'm a c++ noob
void printLength(int inputArray[]) {
cout << "This is my value when finding the length in ANOTHER function: " << sizeof(inputArray)/sizeof(int) << endl;
}
int main()
{
int testArray[] = { 1, 2, 3, 4, 5, 6 };
printLength(testArray);
cout << "This is my value when finding the length in the main function: " << sizeof(testArray)/sizeof(int) << endl;
}
This is my output
This is my value when finding the length in ANOTHER function: 2
This is my value when finding the length in the main function: 6

Why does conceptual storage allocation differ from the actual? [duplicate]

This question already has answers here:
Pointer subtraction confusion
(8 answers)
Closed 6 years ago.
I have a puzzling question (at least for me)
Say I declare an integer array:
int arr[3];
Conceptually, what happens in the memory is that, at compile time, 12 bytes are allocated to store 3 consecutive integers, right? (Here's an illustration)
Based on the illustration, the sample addresses of
arr[0] is 1000,
arr[1] is 1004, and
arr[2] is 1008.
My question is:
If I output the difference between the addresses of arr[0] and arr[1]:
std::cout << &arr[1] - &arr[0] << std::endl;
instead of getting 4,
I surprisingly get 1.
Can anybody explain why it resulted to that output?
PS: On my computer, an int is 4 bytes.
Pointer arithmetic automatically divides the value by the size of the base type so this is not surprising at all since one would expect to get 4 / 4 which is 1. Cast to unsignd char * to see the difference.
#include <iostream>
int
main(void)
{
int arr[2];
std::cout << &arr[1] - &arr[0] << std::endl;
std::cout << reinterpret_cast<unsigned char *>(&arr[1]) -
reinterpret_cast<unsigned char *>(&arr[0]) << std::endl;
return 0;
}