Reputation: 97
I am new in C++. I generally program in C#, so I'm having troubles with arrays and loops. When I try to print content of dynamic array using a loop, it says corrupted requested area... For example I will give it recognize the condition used with content of array but doesn't print content of it:
// Array.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void main()
{
int size=3;
int *p;
int myarray[10];
myarray[3]=4;
p=new int[size];
p[2]=3;
if(myarray[3]==4){
cout << myarray[3] +"/n";
cout << "Why?";
}
else
cout << "Not equal " << endl;
cin.get();
delete [] p;
}
Upvotes: 0
Views: 167
Reputation: 61
While a solution has been given:
cout << myarray[3] << "\n"
the point to get is that myarray[3] is an integer while "\n" is a string and the only way to "add" them together as strings is to first make the integer into a string. The << operator will handle the work of converting myarray[3] into a string, nothing special, and then the second << pumps a new line after it. I personally prefer code like this and find it more flexible, but it may be more that you're looking for at this stage of learning:
printf("%i\n", myarray[3]);
where printf searches for flags and loads in the other arguments as strings and outputs it in one command.
Upvotes: -1
Reputation: 3316
The problem is that myarray[3] +"\n"
.
"\n" represents the memory location of the string "\n". You are trying to add 4 to that location and printing it. This should give you junk data or a hardware exception (resulting in a coredump) if you are accessing a protected memory location.
To get what (i think) you are asking for do,
cout << myarray[3] << '\n'
Upvotes: 0
Reputation: 4186
Code looks fine, unless it should be
cout << myarray[3] << "\n";
Not +
Upvotes: 7