Filling an array using a pointer - c++

Trying to fill an array using a pointer so each index of array contains its' index. The output I am currently getting is this +DD;D;DD. Could someone explain where I am going wrong on this? Thanks.
#include <iostream>
using namespace std;
int main()
{
int NUMBER_ELEMENTS;
cout << "Enter number of elements: ";
cin >> NUMBER_ELEMENTS;
short array1[NUMBER_ELEMENTS];
short *arrPtr;
arrPtr = array1;
short i = 0;
while(i < NUMBER_ELEMENTS)
{
*arrPtr = i;
arrPtr = arrPtr + 1;
cout << "+" + array1[i];
i++;
}
}

Problem 1: The length of an automatic array can not be given at runtime. It must be known at compile time. In order to create an array with dynamic length, you can use std::vector instead.
explain how this is a variable length array?
You can input different values in different executions of the program. Therefore the length varies. Even the value staying the same is by itself not sufficient. The expression used the array length must be a compile time constant expression.
Problem 2: "+" + array1[i] doesn't do what you probably think it does.
The string literal is an array of characters. array1[i] is an integer. When you add an integer to an array using the plus-operator, the array decays to a pointer to first element of the array, and the the pointer is incremented by number given as the operand.
Therefore "+" + 0 increments the pointer by zero places, so the string printed in the first iteration is "+". "+" + 1 increments the pointer by one places. After the + character, there is only the null terminator, so the printed string is empty. After that iteration, the later iterations overflow the array, and the behaviour of the program is undefined.

Related

What's being compared to the last element of the array?

There's a behavior that I don't understand, the c variable is supposed to increase by one every time an element of the array isn't equal to the one next to it, but there's one increment that's done automatically which increases c by one. I think this is because the last element of the array is compared to something which isn't equal to it. Why is this happening? Or if I'm right what's the thing that the last element is compared to?
#include <iostream>
int main() {
int n, c = 0;
std::cin >> n;
std::string s[n];
for (int i = 0; i < n; i++) {
std::cin >> s[i];
}
for (int i = 0; i < n; i++) {
if (s[i] != s[i+1]) {
c++;
}
}
std::cout << c;
}
std::string s[n]; is creating what is known as a "Variable-Length Array", which is NOT part of standard C++, but is supported as an extension by some compilers. Don't rely on this. Use std::vector instead for a dynamic-length array whose length is not known until runtime.
But, more importantly, your 2nd loop has undefined behavior. The valid indexes for the s[] array's elements are 0..n-1, so on that loop's last iteration, s[i] accesses the last string in the array, and s[i+1] accesses out of bounds, so the value that s[i] is compared to is indeterminate (if the code doesn't just crash outright from accessing invalid memory).
s[s.length()] == ‘\0’
From here: https://www.cplusplus.com/reference/string/string/operator%5B%5D/
“If pos is equal to the string length, the function returns a reference to the null character that follows the last character in the string (which should not be modified).”

Multiplying and displaying the values of an array in C++

I am trying to complete a C++ exercise in which an array is displayed and the user is prompted to input a multiplier, which will result in the initial numbers that were displayed being multiplied by the user's input. Here is the code that I have so far:
#include <iostream>
using namespace std;
int main()
{
int array[5] = { 1, 2, 3, 4, 5 };
for (const auto& a : array)
{
std::cout << a << std::endl;
}
double multiplier;
cout << "Input a multiplier: ";
cin >> multiplier;
for (int array = 1; array <= 5; ++array)
{
array == multiplier * array;
std::cout << array << std::endl;
}
}
When it runs, it prints the correct array, with a newline being created after each array value, and prompts the user for the multiplier. However, when the multiplier is inputted, the values do not change. Here is an example output:
1
2
3
4
5
Input a multiplier: 2
1
2
3
4
5
The goal is to get this output:
1
2
3
4
5
Input a multiplier: 2
2
4
6
8
10
Any help or code improvement would be appreciated, as figuring out how to multiply and display the multiplied values is the only thing needed to be done in order to complete the exercise. Thank you in advance!
There are three big issues with your code:
1. Naming conventions.
Do not name your array and your temporary for loop variable the same thing. This will cause an issue further down the line, which I'll illustrate.
2. Incorrect operator
As minterm has mentioned, you are using a comparison operator instead of the equal operator. But that alone will not fix your issue.
3. Not accessing array values
You are not actually multiplying the array values with the multiplier. You have to access the elements, which means you cannot start the index at 1.
for (int i = 0; i < 5; i++){
array[i] *= multiplier
cout << array[i] << endl;
}
Use = instead of ==. Currently, it just evaluates a logical statement instead of setting it to a new value.
Also, you need to change "int array" in the for loop to a different name so as to not get it confused with the array called array. Call the variable in the for loop something else, like "int i".
So then the line in question would not be "array == multiplier*array", but instead something like "int j = multiplier * array[i]", and then have it print out j instead of array.
A simpler approach would be to use another range-based for loop instead of the indexed version:
for (auto& a : array)
{
a *= multiplier;
std::cout << a << std::endl;
}
If you don't need to update the array itself (after all, your code doesn't actually read from the array again), then you a very similar, though more straightforward version might be applicable:
for (const auto& a : array)
{
std::cout << a * multiplier << std::endl;
}
You have quite a few things going on that are incorrect.
First is your over scoping (maybe not the right term) the array value.
You have an array value declared outside of your for loop, and you're using the value array again inside of the for loop for the counter. So you're not actually doing anything to your array. You're actually trying to do something to the initialization variable.
Second you're using == instead of =
You're using a comparison operator (==) instead of an assignment operator (=), but there's other big no no's going on.
array is an int[5] not just an int
To actually modify each element of your array, you need to reference the index by saying array[index] where index is a value of 0 to length of array - 1, so 4 in your case.
You're using a double multiplier and trying to apply it to an int *
If you try to multiply by a double value like 2.5, your array values are going to be int's and not a number with a decimal value. You should make your int array [] into a double array []
Not accessing your array, starting from index 0
When looping through an array, the first index is always 0. You're using array = 1 and array <= 5. This would skip your first index, and give you an out of bound index at the end. You should use int index = 0; index < 5; index++; instead.
You're trying to print array
Since array is an int [] printing array in the for loop like that will just give you the address of where the array is. You'll have to either print out each index or use the enhanced for loop method after you've applied your multiplier.
If you're wanting to use your above implementation, do this
for (int index = 0; index < 5; index++)
{
array[index] *= multiplier; // Or you can use array[index] = multiplier * array[index]
std::cout << array[index] << std::endl;
}

How is this particular code processed in C++14

I know there is a bug in the code, but I am interested to know exactly how C++14 processes the code to output this
3
þÿÿt
With this code
#include <iostream>
void pretty_print(int,int,int);
int main()
{
srand(time(0));
const int LIM = 100;
int a = rand()%LIM;
int b = rand()%LIM;
int c = rand()%LIM;
if(a+b+c<500)
{
pretty_print(a,b,c);
}
else throw new std::invalid_argument("FOOBAR");
return 0;
}
void pretty_print(int a, int b,int c)
{
std::string ans = "";
int count = 0;
if(a!=0)
{
count++;
ans+=(a+" ");
}
if(b!=0)
{
count++;
ans+=(b+" ");
}
if(c!=0)
{
count++;
ans+=(c+" ");
}
std::cout << count << "\n";
std::cout << ans << "\n";
}
P.S. I have deliberately tried to add an integer to a string without conversion in order to examine why the output is such. I want to know why adding an integer without conversion to a string results in such a behaviour.
I want to know why adding an integer without conversion to a string results in such a behaviour.
A string literal is an array of characters. In a value context (such as as an operand of +), an array will be converted into pointer to first element. This implicit conversion is called decaying.
Adding an integer n to a pointer (to an element of an array) will result in a pointer to nth successive sibling of the originally pointed element. For example, "abcd" + 1 will result in a pointer to the characer b. This is called pointer arithmetic.
You generate numbers up to 100, so you end up getting a pointer to up to hundredth index of the string literal. However, the length of the string literal is only 2 (the length of the array includes the null terminator in addition to the length of the string itself), so unless you happened to generate only zeroes and ones, those pointers will be outside the bounds of the string literal.
When a character pointer is passed to the compound assignment operator of std::string, that pointer will be treated as a null terminated pointer to a character string and the pointed object will be accessed.
The behaviour of accessing an array out of bounds is undefined.
In C++ a string literal like e.g. " " is really an array of constant characters. As such it will decay to a pointer to its first element.
What you're doing with a+" " is pointer arithmetic: You add the value of a to the pointer pointing to the first character of " ". In other words, a + " " is equal to &" "[a]. (It helps knowing that for any pointer or array p and index i the expression *(p + i) is exactly equal to p[i].)
Unless the values of your variables is 0 (or 1, which is the index of the terminator), then the values as indexes will be way out of bounds of the array holding " ", leading to undefined behavior.

Pointer for array to calculate average in C++

I got a question on pointer in C++ :
Write a function that computes the average value of an array of floating-point data:
double average(double* a, int size)
In the function, use a pointer variable, not an integer index, to traverse the array elements.
And here is my solution :
int main()
{
const int size = 5;
double num_array[] = {2,2,3,4,5};
double* a = num_array;
cout << average(a,size);
cout << endl;
system("PAUSE");
return 0;
}
double average(double* a,const int size)
{
double total = 0;
for (int count =0; count< size; count++){
total = total + *(a + count);
}
return total/size;
}
It works fine but I have question on the for loop on pointer in average function. If I replace the statement in for loop with :
total = total + a*;
(I thought we supposed to do like this to add up all the number in array but unfortunately it gives me the wrong answer)
So what does the *(a + count) do? If possible, can somebody please simply brief me on how it works?
Thanks in advance.
a is a pointer to a double.
If you write *a, this pointer gets dereferenced and you get the data where the pointer points at, i.e. the double value. Note that the asterisk has to be in front of the pointer. (It's a "prefix" unary operator.)
a* is no valid syntax (it tries to multiply a with something which still has to follow ...)
a + count is pointer arithmetic. It gives you a but with count numbers of elements offset to the original a pointer. So it now points to the count-th element in the array.
*(a + count) now dereferences exactly this pointer, which gives you the count-th element of the array.
a[count] is exactly the same; it's just a nicer syntax.
Note: You can also use a++ in your loop. What it does is it increments the pointer by one position in the array. The next time you dereference a using *a, it returns the next entry. So your loop can be rewritten like this:
double total = 0;
for (int count = 0; count < size; count++){
total = total + *a; // Access the element a currently points to
a++; // Move the pointer by one position forward
}
You can even combine the increment and dereferencing operations into one expression. The postfix-increment syntax a++ will return the old pointer and increment the pointer by one position. Dereferencing a++ now means that you dereference the old pointer.
double total = 0;
for (int count = 0; count < size; count++){
total = total + *(a++);
}
The second note I want to give you is that you don't need your integer variable here to count the element. Since your pointer now already carries the information, your counter is now only used to stop the loop. This can also be done by comparing the pointer with some "end pointer", which we keep in a variable:
double total = 0;
double *end = a + size; // Store the end of the array
while(a < end) {
total = total + *(a++);
}
As you can see, I converted the for loop into a while loop since I no longer need to initialize or increment something (remember: going to the next entry of the array is done in the body!).
I hope this illustrates pointer arithmetic a little bit. You can "calculate" with pointers similarly as with indexing variables (your count variable). You can even subtract them to calculate offsets between pointers, for example.
* is the dereferencing operator, operating on the address a increased by count.
Read Pointers.

C++: array for loop printing addresses instead of values

this was an example given to us in class. Could someone explain to me why this prints 29 addresses instead of 29 "0" (zeroes) ?
int num[29]; is an array which has set aside 29 addresses for 29 integers -i get that part, but in the for loop you arent u printing the values IN those addreses rather than the addresses themselves?
also, whats the difference between (num+i) and (num[]+i)?
I'm a little confused..
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int num[29];
for (int i=0;i<29;i++)
cout << (num+i) << endl;
return 0;
}
The reason for printing addresses is that
(num+i)
Is the address of the ith element of the array, not the ith element itself. If you want to get the ith element, you can write
*(num + i)
Or, even better:
num[i]
As for your second question - the syntax (num + i) means "the address i objects past the start of num, and the syntax (num[] + i) is not legal C or C++.
Hope this helps!
A declaration such as:
int num[29];
defines a contiguous array of 29 integers.
To access elements of the array use num[i] where i is the index (starting at 0 for the 1st element).
The expression num on its own gives a pointer (memory address and type) of the first element of the array.
The expression ptr + i (where ptr is a pointer and i is an integer) evaluates to a pointer that is i positions (in units of the type of pointer) after ptr.
So num + i gives a pointer to the element with index i.
The expression &a gives a pointer to some object a.
The expression *ptr gives the object that some pointer ptr is pointing at.
So the expressions a and *(&a) are equivalent.
So num[5] is the same as *(num+5)
and num+5 is the same as &num[5]
and num is the same as &num[0]
When you print a pointer with cout it will show its address.
When you print an object it will print the value of the object.
So
cout << num + 5;
will print the address of the 5th (zero-indexed) element of num
and
cout << num[5];
will print the value of the 5th (zero-indexed) element of num