hardcoding 2D array values - c++

Trying to insert values into a 2D array, but the output isnt giving my values, instead random letters
int myArr[8][2] = {700,730,760,790,810,840,910,1000}{0.011,0.035,0.105,0.343,0.789,2.17,20,145};
cout << myArr << endl;
system("Pause");
How should I adjust the code, or is it easier to use a text file and insert?

Numerous problems:
the array dimensions are wrong
you don't have outer braces or a comma for the nested arrays
you're trying to store double precision floating point values in an int array
you can't use cout with an entire array.
The array declaration should probably be something like this:
double myArr[2][8] = { {700,730,760,790,810,840,910,1000},
{0.011,0.035,0.105,0.343,0.789,2.17,20,145} };
and to output the contents you could do something like this:
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 8; ++j)
{
cout << " " << myArr[i][j];
}
cout << endl;
}
Live Demo

First - you can't print the whole array just by using cout << myArr, you need to iterate over the elements of the array using a for loop.
Second - you are trying to put decimal values into an integer array which will truncate all of the decimals.
Third - Your array should be sized myArr[8][2] not myArr[2][8]. I'm surprised your compiler lets you get away with this. You should probably look into using a different compiler.

You need to iterate through each row and column, otherwise you're just printing out the pointer value of the array handle.
for (int i=0;i<8;i++){
for (int j=0;j<2;j++){
cout << myArr[i][j] << " ";
}
cout << endl;
}
system("Pause");

Related

Get value of twodimensinal dynamic array from storred pointer adress

Im trying to get all values of a dynamic array initialised like this:
string** structure= new string*[nombre_attributs]();
for(int j=0; j<nombre_attributs; j++){
structure[j]= new string[2]();
}
I can fill it with no problem. I then keep a pointer to this array in an array of pointers called adresses_structures.
How can I now acces the data in this array?
This attempt:
string *test = adresses_structures[i];
cout << "Value:" << *(test+0)<<endl;
cout << "Value:" << *(test+1)<<endl;
cout << "Value:" << *(test+2)<<endl;
doesn't work for all values from the second line in the array.
I have tried tons of combinations as
for(int k=0; k<2;k++){
for(int j=0;j<2;j++){
cout << "Truc:" << *(test + k*2 + j)<<endl;
}
}
but nothing seem to be able to get the values on the second line.
Thanks for any advice.
I assume, that string** structure is the same as adresses_structures here.
When You are doing *(test+1) You move by one byte from test address. You should move by size of string object (check sizeof(string)). Like this: *(test+1*sizeof(string)) or *(test+2*sizeof(string))

Output of an expanded array returns unexpected answer

I have finished writing a program that included reversing, expanding and shifting arrays using the pointer requirement asked by the professor. Everything compiles but the answer from the expand function does not return what I wish: adding 0s after the old user input array which asks for the size of the array and the numbers you wish to put into the array. I think my problem may lie from the fact that I include a pointer on something that might not have a reference in the program. Below is my code:
// *numPtr refers to my old user input array and int tamaño is the size of the array
void expandArray(int *numPtr, int tamaño) {
int *nuevoArray = new int[tamaño *2];
for (int i = 0; i<tamaño; i++) {
nuevoArray[i] = numPtr[i];
}
for (int i = tamaño; i < (tamaño*2); i++) {
nuevoArray[i] = 0;
}
std::cout << nuevoArray << " ";
}
As I said, my theory of the code not compiling the way I wish is because I use the *nuevoArray and it has no reference in my main code, but then again, I am just a beginner with C++. I was thinking of just doing a vector, but I think I would not follow the pointer requirements placed by the professor.
If you want to print the contents of nuevoarray, just use a for loop like this:
for (int i = 0; i < (tamaño*2); i++) {
std::cout << nuevoArray[i] << " ";
}
std::cout << "\n";
Also, since you are using new[] to create the array, you should not forget to delete[] it!
you can print your array by using
for (int i = 0 ; i < tamano * 2 ; ++i) {
std::cout << nuevoArray[i] << " ";
}
std::cout << std::endl;
or in c++11
for (auto i : nuevoArray) {
std::cout << i << " ";
}
std::cout << std::endl;
PS: The std::endl will return to the start of the new line and flush the cout buffer.
Your code does appear to be allocating a larger array and correctly copying data from numPtr into the new array and also correctly filling the remainder of the new array with zeros.
You don't explicitly say what you expect this function to output, but I'm guessing you expect it to print out the contents of the new array, and that you believe there's a problem because instead of that, you're seeing it print something like "0x7fb46be05d10".
You're not correctly printing the array out. Instead you're printing the memory address of the first element out. If you want to see the contents, then you need to loop over the elements of the array and print each one out individually.
Here's a function showing one way of doing that:
#include <algorithm>
#include <iterator>
void printArray(int *arr, int n) {
std::copy(arr, arr + n, std::ostream_iterator<int>(std::cout, " "));
}
Now you can replace the line std::cout << nuevoArray << " "; in your existing code with printArray(nuevoArray, tamaño*2);
(Also it sounds like whoever is teaching you C++ should take a look at this presentation from the recent C++ conference, CppCon 2015: Stop Teaching C)

Code crashes. Trying to remove characters from char array C

I am basically trying to store everything after a certain index in the array.
For example, I want to store a name which is declared as char name[10]. If the user inputs in say 15 characters, it will ignore the first five characters and store the rest in the char array, however, my program crashes.
This is my code
char name[10];
cout<< "Starting position:" << endl;
cin >> startPos;
for(int i= startPos; i< startPos+10; i++)
{
cout << i << endl; // THIS WORKS
cout << i-startPos << endl; // THIS WORKS
name[i-startPos] = name[i]; // THIS CRASHES
}
For example, if my name was McStevesonse, I want the program to just store everything from the 3rd position, so the end result is Stevesonse
I would really appreciate it if someone could help me fix this crash.
Thanks
Suppose i is equal to 3. In the last iteration of the loop, i is now equal to 12, so substituting 12 in for i, your last line reads
name[12-startPos] = name[12];
name[12] is out of bounds of the array. Based on what you have shown so far, there is nothing but garbage stored in name anyway before you start doing this assignment, so all you're doing is reorganizing garbage in the array.
Please in future: post full compilable example.
A simple answer is that your array maybe is out of bound, since you don't provide full example its hard to know exactly.
Here is a working example:
#include <iostream>
using namespace std;
int main() {
int new_length, startPos;
int length = 15;
char name[15]= "McStevesonse";
cout<< "Starting position:" << endl;
cin >> startPos;
if(new_length <1){ // you need to check for negative or zero value!!!
cout << "max starting point is " <<length-1 << endl;
return -1;
}
new_length=length-startPos;
char newname[new_length];
for(int i= 0; i<new_length; i++){
newname[i] = name[i+startPos]; // THIS CRASHES
}
cout << "old name: " << name << " new name: " << newname << endl;
return 0 ;
}
To put it simply, change this:
for(int i= startPos; i< startPos+10; i++)
To this:
for(int i= startPos; i<10; i++)
You should be fine with that.
Explanation:
At some point, when you use the your old loop, this name[i-startPos] = name[i] would eventually reach an array index out of bounds and causes the crash.
Don't forget to clean up/hide the garbage:
Doing so, would cause the output to produce some kind of garbage outputs. If you got a character array of 'ABCDEFGHIJ', and have chosen 3 as the starting position, the array would be arranged to 'DEFGHIJHIJ'. In your output, you should atleast hide the excess characters, or remove by placing \0's

Using ASCII characters in C++ program

I've been trying to print out _ <------ this character in a 2D array... But when I
tried compiling the code, it returned some garbage numbers. I think I'm doing something wrong... can anyone please help me out to solve this problem ?
void main (){
int A[9][9];
for (int i=0; i<9; i++){
for (int j=0; j<i; j++){
A[i][j]= '_';//I am doing this part wrong.
}
}
for (int r=0; r<9; r++) {
for (int c=0; c<9; c++)
cout << setw(3) << A[r][c];
cout << endl;
}
system("pause");
}
A is an int array. So cout would try to print an integer. Try cout << char(A[r][c]);
The std::cout::operator<< operator is overloaded for several data types in order to facilitate (automagically-)formatted output. If you feed it an int, then it will print a number. If you give it a char, it will try to print it as a character. So either declare your array as an array of char, or cast the array member when printing:
cout << static_cast<char>(array[i][j]) << endl;
1. Assign the ASCII value to integer array rather than '_'. It will work even without change; but i feel it looks cleaner.
A[i][j]= 95; // try this instead of '_'
While printing, cout can print any data type without casting, but since we are looking for character to be printed, try explicit conversion.
cout << setw(3) << char(A[r][c]);
Not sure about the compiler you are using, but its a better practice to initialize the array to avoid garbage value tampering with your output

Double dimensional array to single dimensional array

I am just doing an experiment to put values in double dimensional array to a single dimensional array. Below is my code and result:
#include <iostream>
using namespace std;
int main()
{
int p[1][1];
int arrayA[4];
for(int i=0;i<2;i++){
for(int j=0;j<2;j++)
{
p[i][j] = i+j;
}
}
int *a = &(p[0][0]);
for(int k=0;k<4;k++)
{
arrayA[k] = *a;
cout << "*a: " << *a << endl ;
cout << "array[k] :" << arrayA[k] << endl;
cout << "a: " << a << endl;
cout << "---------------------------" << endl;
a++;
}
system("PAUSE");
}
and the result is:
But I have no idea why it missed the value of p1[0], which value should be 1. But instead, I got a weird number where it is from. Because this is weird to me that I can put the last number in the double dimensional array to the single dimensional array but not the number before.
So I hope somebody can tell me what happen to me code or my method of thinking. Thank you.
This results in an out of bounds on array p:
int p[1][1];
int arrayA[4];
for(int i=0;i<2;i++){
for(int j=0;j<2;j++)
{
p[i][j] = i+j;
}
}
Indexes on arrays run from 0 to N - 1, where N is the size of the array.
The problem is that you wrote:
int p[1][1];
Remember that in C, and in C++, the number on elements for dimensions is the true number that you mean the vector or matrix to have. However, their indexes run from 0 to n-1 (where n is the number you wrote). So your declaration of p should be:
int p[2][2];
instead.
Hope this helps.
You wrote int p[1][1] but I think you meant int p[2][2].