I got a trouble with C++ array initialization - c++

I am new to C++. Recently, I have been stuck with a simple code of C++ features. I will be very grateful if you can point out what exactly the problem. The code as follows:
// used to test function of fill
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int val = 0;
int myarray[8];
//fill(myarray,myarray+2,1);
for(;val < 8;++val){
cout << myarray[val];
cout << endl;
}
}
And the it has printed out:
-887974872
32767
4196400
0
0
0
4196000
0
The question is I thought the default value for array without initialization (in this case its size is 8) would be (0,0,0,0,0,0,0,0). But there seemed to be some weird numbers there. Could anyone tell me what happened and why?

The elements are un-initialized, i.e, they contain garbage value.
If you want to initialize the array elements to 0, use this:
int myarray[8] = {};

Initial values are not guaranteed to be 0.

If you want to get a array have a initial value,you can do like this:
int *arr = new int[8]();

int myarray[8];
This is a simple declaration of an Array i.e you are telling the compiler "Hey! I am gonna use an integer array of size 8". Now the compiler knows it exists but it does not contail any values. It has garbage values.
If you intend to initialize array (automatically) then you need to add a blank initialization sequence.
int myarray[8]={}; //this will do
Happy Coding!

Related

C++ writing to myArray[0] and setting myInt = myFloat, why is this working?

I'm playing with a function to get used to some C++ syntax.
Now I think, I might have misunderstood:
I'm writing to a static (?) array I had defined as myArray[0] for experimenting.
So it seems NOT to be static, but sizeof(myArray) always returns 0 (?)
but I can find mem address for each item (while I have no idea, how to get the number of items this way).
The other thing I don't understand, is why I can write myInt = myFloat?
So, what IS a static array? And should I better use <vector> for an array of undefined length?
(You could find the whole code here int2bin main.cpp)
#include <iostream>
//#include <regex>
int main()
{
while(true) {
//VARS
unsigned int arrBin[0], intNum; //working, if set [0]! NOT static???
unsigned int *pArr0 = &arrBin[0];
unsigned int *pArr1 = &arrBin[1];
std::cout << sizeof(arrBin) << '\n'; // 0 => sizeof() here items and not mem space?
std::cout << pArr0 << '\n';// 0x7fff12de6c38
std::cout << pArr1 << '\n';// 0x7fff12de6c3c
int i;
float refNum;
std::cout << "\n\nEnter a number to convert: ";
// GET INPUT
std::cin >> refNum; // float
intNum = refNum; // get int of the dec for comparing. Why does this "int = float" work???
unsigned int arrBin[0]
The size of an array variable must not be 0. The program is ill-formed. Don't do this.
unsigned int *pArr1 = &arrBin[1];
Here, you use subscript operator beyond the bounds of the array (beyond one past last element), so the behaviour of the program is undefined. Don't do this.
(while I have no idea, how to get the number of items this way).
The number of items is 0 (or would be if that was allowed in the first place).
The other thing I don't understand, is why I can write myInt = myFloat?
You haven't even declared such identifiers.
I'm writing to a static (?) array I had defined as myArray[0] for experimenting.
By 'static' you probably mean 'fixed-sized'. static means something totally different, see https://www.geeksforgeeks.org/static-keyword-cpp/.
So it seems NOT to be static
It is not static, hence, it's not surprising that it's not static.
but sizeof(myArray) always returns 0
Its size is 0, as the size of 0 was specified. While this is not supported by the standards, it's possible that some compilers allow it.
but I can find mem address for each item (while I have no idea, how to get the number of items this way).
&arr[i] yields the address.
The other thing I don't understand, is why I can write myInt = myFloat?
Integer numbers are always real numbers, but real numbers are not always integer numbers. So, how would you store 0.5 as an integer? You could cast it or you could round it.
So, what IS a static array?
In the link I have provided you, it is mentioned that static variables in a function are variables for whom memory is allocated for the whole duration of a program. Hence, a static array is an array declared with the static keyword for which space are allocated for the whole lifecycle of your program. No such array was declared in your function.
And should I better use for an array of undefined length?
This is opinionated. You could create a pointer and navigate to items using pointer arithmetics, achieving the same behavior as with arrays, but without the length being fixed and with a slightly different syntax. Or you could use a library, a vector or whatever fits your task and taste.

Array Function. Would appreciate a little clarification

I have a question regarding a school lab assignment and I was hoping someone could clarify this a little for me. I'm not looking for an answer, just an approach. I've been unable to fully understand the books explanations.
Question: In a program, write a function that accepts three arguments: an array, the size of the array, and a number n.
Assume that the array contains integers. The function should display
all of the numbers in the array that are greater than the number n .
This is what I have right now:
/*
Programmer: Reilly Parker
Program Name: Lab14_LargerThanN.cpp
Date: 10/28/2016
Description: Displays values of a static array that are greater than a user inputted value.
Version: 1.0
*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void arrayFunction(int[], int, int); // Prototype for arrayFunction. int[] = array, int = size, int = n
int main()
{
int n; // Initialize user inputted value "n"
cout << "Enter Value:" << endl;
cin >> n;
const int size = 20; // Constant array size of 20 integers.
int arrayNumbers[size] = {5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}; // 20 assigned values for the array
arrayFunction(arrayNumbers, size, n); // Call function
return 0;
}
/* Description of code below:
The For statement scans each variable, if the array values are greater than the
variable "n" inputted by the user the output is only those values greater than "n."
*/
void arrayFunction(int arrayN[], int arrayS, int number) // Function Definiton
{
for (int i=0; i<arrayS; i++)
{
if (arrayN[i] > number)
{
cout << arrayN[i] << " ";
cout << endl;
}
}
}
For my whole answer I assume that this:
Question: In a program, write a function that accepts three arguments: an array, the size of the array, and a number n. Assume that the array contains integers. The function should display all of the numbers in the array that are greater than the number n .
is the whole assignment.
void arrayFunction(int[], int, int); is probably the only thing you could write. Note however that int[] is in fact int*.
As others pointed out don't bother with receiving input. Use something along this line: int numbers[] = {2,4,8,5,7,45,8,26,5,94,6,5,8};. It will create static array for you;
You have parameter int n but you never use it.
You are trying to send variable to the function arrayFunction but I can't see definition of this variable!
Use something called rubber duck debugging (google for it :) ). It will really help you.
If you have some more precise question, ask them.
As a side note: there are better ways of sending an array to the function, but your assignment forces you to use this old and not-so-good solution.
Would you use an if else statement? I've edited my original post with the updated code.
You have updated question, then I update my answer.
First and foremost of all: do indent your code properly!!!
If you do that, your code will be much cleaner, much more readable, and it will be much easier understandable not only for us, but primairly for you.
Next thing: do not omit braces even if they are not required in some context. Even experienced programmers only rarely omit them, so as a beginner you should never do so (as for example with your for loop).
Regarding if-else statement the short answer is: it depends.
Sometimes I would use if (note: in your case else is useless). But other times I would use ternary operator: condition ? value_if_true : value_if_false; or even a lambda expression.
In this case you should probably settle for an if, as it will be easier and more intuitive for you.
Aside from the C++ aspect, think about the steps you need to do to figure out if a number is greater than a certain value. Then do that for all the numbers in the array, and print out the number if it's greater than n. Since you have a 'for' loop, it looks like you already know how to do a loop and compare numbers in C++.
Also, it looks like in your arrayFunction you are trying to input values? You can't input a whole array's worth of values in a single statement like you appear to be trying (also, 'values' is not the name of any variable in arrayFunction, so that would not be recognized when you try to compile it).

accessing array with pointer giving an extra element

Ok a very basic question, but I am stuck at it. I cannot figure out the extra mysterious value at the end of the array. I just tried to traverse the array through its base address, plain and simple. But the garbage value at the end of the array remains constant every time I execute it
g++ complier 64 bit machine.
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
void printarray(int * arr){
while(*(arr)){ cout<<*arr<<" "; arr++; }
cout<<endl;
}
int main(){
int arr[] = { 3,2,4,1,5 };
printarray(arr); // prints 3,2,4,1,5,32765
return 0;
}
EDIT 1: I understand that the while will terminate whenever it comes across a 0 in the array , or if no 0 is found will go insane . But still I would want you guys to look at the following test cases
3,2,0,4,1,5 // outputs 3,2
3,2,4,1,5,7,8,9 // outputs same array correctly
3,2,4,1,5,7,8,9,10 // outputs array+ 1 varying garbage at last
//observations, this method works for even sized arrays not containing
//0, while for odd it emits an additional garbage value.
My question is if the while only breaks at 0 , why does it break at
arrayLength+1 everytime ? Also what's with this even odd length ?
An array is not terminated in any special way. What you are trying to do is not working because while(*arr) relies on a wrong assumption: that there is a 0 element at the end of the array (a sentinel) but you declare the array a {3,2,4,1,5} so there is no end element.
I think your misconcept comes from the fact that you are not getting the point that an int* is just a memory address, whenever you increment it by ++arr you are basically adjusting it by sizeof(int). Nothing more, when you reach the end of the array then the address just points after the array, to whatever value could be there.
You get the extra element(s) because there is nothing about a pointer that tells the compiler how many elements the pointer points to. When you do
while(*(arr)){...}
The while loop will continue running untill *arr == 0. Since you array doesn't contain a 0 it will keep going past the end of the array untill it finds a 0. This is undefined behavior as you are accessing memory you do not own with that pointer.
I think you may be confusing how char arrays(c-strings) work compared to other data types. When you have
char arr[] = "something";
while(*(arr)){...}
This ends at the end of the array as c-strings get a null terminator(0) added to the end of the string automatically. This allows you to do things like the above loop as you know that null terminator will be there and if it is not then that is on the person you created the string.
An array decays into a pointer when passed to a function, and this function knows nothing about the array's length.
That while(*arr) stuff is incorrect. It will stop only when some value this pointer points to is zero. But who said a zero is placed at the end of an array?? When you increment arr, you can easily get out of bounds of your array (the function doesn't know its size!), and then *arr will give you whatever the heck is stored at the memory address arr points to at the moment.
To iterate over an array, pass the array itself and its length. Otherwise this will iterate over and over until the value of *arr will be zero.
Pointers aren't terminated in C++ by any character.
This works on other types like char* only because it's terminated by an \0(0).
An INT-Array u need to count the Elements before you can pass them into something like that, for example here with the ending 5 from your Pointer:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void printarray(int * arr){
int *saved=arr;
while(*saved!=5)
{
cout<<*saved++<<" ";
}
*saved=0;
cout<<endl;
}
int main(){
int arr[] = { 3, 2, 4, 1, 5 };
printarray(arr); // prints now without ending 5.
return 0;
}
Otherwise, you need to pass the counter of elements.
There is no way C++ could know how many elements your pointer points to.

Assigning value to struct's field, change also other variable

Simple code
#include <iostream>
using namespace std;
struct foo {
int bar;
};
struct foo tab[2];
int sum = 0;
int main()
{
tab[2].bar = 3; //this change 'sum' value!
cout << sum << endl;
return 0;
}
result in 3 instead of 0. It is unbelievable, so problably I am missing something. What I have done wrong?
Arrays start at 0, so tab[2] would be the third element, but you only allocated 2 of them.
In this case, sum is in the memory directly after tab, so when you go to where the third tab would be, you're actually in the memory for sum.
Notice that you access tab[2] which is an overflow (its size is 2 so valid indices are 0 and 1).
So tab[2] accesses the memory address of sum.
When you declare your variable
struct foo tab[2];
tab[2] does not exist.
You can only do
tab[0].bar = 3
tab[1].bar = 3
because arrays index starts from 0 and ends at arraySize-1.
If you look closely tab has a length of 2. By accessing the index 2, you are accessing memory out of the tab, which means you are accessing sum.
This is the reason why you are changing sum.
First of all, turn on compiler warnings! If you'd allow the compiler to help you, then it would very likely point out the exact error in this line:
tab[2].bar = 3; //this change 'sum' value!
Depending on which compiler you use, the warning may be as follows:
warning: array subscript is above array bounds
struct foo tab[2]; has two elements with indices 0 and 1, you try access a non-existing 3rd element. This results in undefined behaviour of your program. Whatever results you got, it was just random. Your program could also randomly crash.
Note that your code is also half C and half C++. That's not good. You don't need to write struct foo when you want to refer to the foo type, it's enough to write foo. Instead of a raw array, std::array<Foo, 2> can be used. And using namespace std; should not be used by default.

Correct pointer arithmetic in C

I am trying to learn pointer manipulation in C, and I am not understanding how part of the code isn't working.
#include <stdio.h>
int main() {
int *alpha[17];
*(alpha+4)= 35;
*(alpha+5)= 35;
*(alpha+12)= 50;
printf("%d", *(alpha+4));
*(alpha+8)=*(alpha+5) + *(alpha+12);
return 0;
}
Why is the line after the printf not working, and causing a crash, when the previous lines ran perfectly? I am trying to get the 9th value to equal the sum of the 6th and 13th value.
int *alpha[17]; creates array of pointers.
If you want array of int, use int alpha[17];
Your assignations are succesful because of implicit cast from int to pointer. (I hope you are getting warnings)
Adding two pointers is not only non-sensical, but also not allowed in C.
This post covers why adding two pointers is forbidden in C++, but arguiments are applicable to C also.
You have created an array of pointers but have not array of ints.
You should use:
int alpha[17];