My Code:
#include <iostream>
#include <cstdlib>
using namespace std;
int *p;
void fun(int *arr, int n)
{
p = (int *)malloc(sizeof(int) * (n + 1));
cout << sizeof(p) / sizeof(int) << " " << sizeof(p) << " " << sizeof(int) << endl;
}
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
fun(arr, n);
return 0;
}
Input:
4
2 1 4 3
Output:
2 8 4
Expected Output:
5 20 4
The code returns an incorrect value of the size which is being allocated to the array using malloc. I identified this problem when I used memset(p, -1, sizeof(p)))and the array was incorrectly initialized. Please help. Thanks in advance.
Because p is a pointer sizeof(p) will return 8 (or 4 on 32 bit systems). Because that is the size used by p. The memory size used by the structure p points to is another story
Related
I have a variable k of type int to set the length of a dynamically allocated int array:
int *Numbers = new int[k];
But because of this I cannot iterate over the array, I get an error:
"no matching begin function was found required for this range-based for statement"
I also cannot get the length of the array using size();
Here's the complete code:
#include <iostream>
using namespace std;
int main()
{
int b, k;
cin >> b >> k;
int *Numbers = new int[k];
for (int i : Numbers) {// (There is a error)
}
for (int i = 0; i < size(Numbers); i++) {
}
}
Prefer using a std::vector instead of a std::array. (Like #tadman mentioned.)
Here is your code using std::vector instead:
#include <iostream>
#include <vector>
int main()
{
int b, k;
std::cin >> b >> k;
std::vector<int> Numbers(b,k); // Fills the vector "Numbers" with nth number of elements with each element as a copy of val.
for (int i : Numbers)
std::cout << i << std::endl;
for (int i = 0; i < Numbers.size(); i++)
std::cout << Numbers[i] << std::endl;
return 0;
}
Say I want 10 elements with the number 5.
Output:
10
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
Also consider not using namespace std;.
The simple and recommended solution is to use std::vector, however if you really want a dynamically allocated array and to use iterator like features on it, you can use iterator_range from boost library, which allows you to create an iterator range for it thus making it usable in range based for loops and in functions like std::size.
Live demo
#include <iostream>
#include<boost/range.hpp>
int main()
{
int k = 5;
int *Numbers = new int[k]{1,4,5,7,8};
auto arr = boost::make_iterator_range(Numbers, Numbers + k);
for (int i : arr) { //range based loop
std::cout << i << " ";
}
std::cout << std::endl << "Size: " << arr.size(); //print size
//or std::size(arr);
}
Output:
1 4 5 7 8
Size: 5
Range-based for loops work with arrays, but not work with pointers. The Actual issue is that arrays is actually a pointer and not an array.try to use simple array.
Using pointers is problematic for many reasons. The simple solution to your problem is to use a vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int b, k;
cin >> b >> k;
vector<int> Numbers(k);
for (int i : Numbers) {
cout << i << endl;
}
for (int i = 0; i < Numbers.size(); i++) {
cout << Numbers[i] << endl;
}
}
C array does not have default iterator and thus there is no begin() and end() functions that are used to iterate over array when you use statment like this:
for (int i : Numbers)
You can check range-for reference:
range_expression - any expression that represents a suitable sequence (either an array or an object for which begin and end member functions or free functions are defined, see below) or a braced-init-list.
Okay, so since the dynamic array does not have a default iterator, do not use the for-each loop, instead consider using the regular for loop.
Also, mind the the size function will not work for an array (or dynamic array) and you need to remember the size, since it's not possible to get the size from the pointer only. Hence, this code would work:
#include <iostream>
using namespace std;
int main()
{
int b, k;
cin >> b >> k;
int *Numbers = new int[k];
const int SIZE = k;
for (int i = 0; i < SIZE; i++) {
cout << i << ' ';
}
}
You need to dereference *Numbers by using the * if you want to iterate over the array because *Numbers is a pointer to an integer which points to the first element of your array.For Example :
#include <iostream>
using namespace std;
int main()
{
int k = 10;
int *numbers = new int[k];
//filling the array
for(int i = 0 ; i < k ; ++i) {
*(numbers + i) = i ;
}
//output array element
for(int i = 0 ; i < k ; ++i) {
cout << numbers + i << " is the address of "<<*(numbers + i) << endl;
}
return 0;
}
The output is :
0x6f1750 is the address of 0
0x6f1754 is the address of 1
0x6f1758 is the address of 2
0x6f175c is the address of 3
0x6f1760 is the address of 4
0x6f1764 is the address of 5
0x6f1768 is the address of 6
0x6f176c is the address of 7
0x6f1770 is the address of 8
0x6f1774 is the address of 9
Unfortunatly, you can't get the size of your array with *Numbers because it's not an array but a pointer.
I'm learning pointers in but I'm stuck on dynamic allocation of arrays.
The code below provides a function to find the element with the lowest value.
A dynamically allocated array is passed as a parameter to it.
#include <cstdlib>
#include <iostream>
using namespace std;
int findMin(int *arr, int n);
int main()
{
int *nums = new int[5];
int nums_size = sizeof(*nums);
cout << "Enter 5 numbers to find the minor:" << endl;
for(int i = 0; i < nums_size; i++)
cin >> nums[i];
cout << "The minor number is " << findMin(*nums, nums_size);
delete [] nums;
return 0;
}
But it return this error:
error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
How can I pass that array to the function?
Just for curiosity: why the for loop allows me to enter 4 value if my array is made up of 5 elements?
How can I pass that array to the function?
nums is already a type int*, you don't need to dereference it:
findMin(nums, nums_size);
why the for loop allows me to enter 4 value if my array is made up of 5 elements?
int nums_size = sizeof(*nums); does not do what you think it does. It's equivalent to sizeof(nums[0]), which is equivalent to sizeof(int), which happens to be equal to 4 at your machine.
There is no way to extract size of array allocated on the heap, you need to save the size on your own:
int nums_size = 5;
int* nums = new int[nums_size];
#include <cstdlib>
#include <iostream>
using namespace std;
int findMin(int *arr, int n){
int mn=INT_MAX;
for(int i=0;i<n;i++){
if(arr[i]<mn){
mn=arr[i];
}
}
return mn;
};
int main()
{
int nums_size = 5;
int *nums = new int[nums_size];
cout << "Enter 5 numbers to find the minor:" << endl;
for(int i = 0; i < nums_size; i++)
cin >> nums[i];
cout << "The minor number is " << findMin(nums, nums_size);
delete [] nums;
return 0;
}
The above code works fine. Your error was in passing the array to the function.
Also to add -
Your code made only 4 iterations coz sizeof(*nums) returned the size of base index element pointed by pointer, i.e ,sizeof(num[0]). So I made a minor change and now it works fine.
#include <iostream>
#include <algorithm>
bool wayToSort(int i, int j) { return i > j; }
bool wayToSortAlt(int i, int j) { return i < j; }
int main()
{
using namespace std;
int size = 5;
int *myArray = new int[size] { 0 };
int option = 0;
cout << "How many numbers do you want to enter?: ";
cin >> size;
cout << "How do you want to sort? ( [1] Greatest [2] Lowest ): ";
cin >> option;
cout << "----\n";
// Get number inputs
for (int count = 0; count < size; ++count)
{
cout << "Enter a number: ";
cin >> myArray[count];
}
cout << "----\nSorted:\n----\n";
// Sort for highest numbers
if (option == 1)
sort(myArray, myArray + size, wayToSort);
else
sort(myArray, myArray + size, wayToSortAlt);
// Print each number
for (int count = 0; count < size; ++count)
{
cout << myArray[count] << "\n";
}
delete[] myArray; // Clean up
myArray = nullptr; //
return 0;
}
I run this code in Visual Community 2013 and if I input a high number such as 10, I get a heap corruption error. From what I have read, the heap corruption error happens when you try to write to an unallocated memory adress, but I don't understand two things:
1) Why does this happen with a dynamic array, and
2) Why does the error only happen when I try to put in a larger number.
Luke,
You have defined the size of the array already. So it is not a dynamic array. It is a pointer to an array that has a size of 5 and can hence only store up to 5 ints.
So you basically have allocated enough space to hold 5 int. This means that if you try to store more than 5, for example the 6th int at index of 5, you are trying to access memory that is not yours to claim.
for example here you have:
[] [] [] [] []
1 2 3 4 5
is good
[] [] [] [] []
1 2 3 4 5 6 7 8 ...
cause the heap corruption.
Might I suggest std::vector ?
I have successfully reversed a 1-D array but when I cout the contents, it prints out the contents then bunch of other numbers.
4
3
2
1
-858993460
-858993460
4
-858993460
-1021245226
12384668
3697177
1
14484784
14501672
-1021245434
0
Press any key to continue . . .
I can't tell why it's printing out those extra numbers. Below is my source code:
#include <iostream>
#include <array>
using namespace std;
void flipRow(int array[], int row) {
int temp;
for (int i = 0; i < sizeof(array)/2; i++) {
//cout << "Hi" << endl;
temp = array[i];
array[i] = array[row-1];
array[row-1] = temp;
row--;
}
}
int main() {
const int ROW = 4;
int array[ROW] = { 1, 2, 3, 4 };
flipRow(array, ROW);
for (int i = 0; i < sizeof(array); i++) {
cout << array[i] << endl;
}
system("pause");
return 0;
}
Are those addresses? Can someone tell why it's printing them out? Thank you.
Modify your for loop in main so the condition part of it becomes i < ROW and modify the for loop in flipRow so the condition part there reads i < row/2. sizeof operator returns the size of your array in bytes. You have four elements in your array and they are of type integer, which on your platform is 4 bytes, so your call to sizeof is returning 16.
this my program to return array from function in c++
#include <iostream>
using namespace std;
int *pTest(){
static int a[] = {2,3,4,6,9};
return a;
}
int main(){
int *x;
x = pTest();
while(*x != NULL){
cout << *x++ << " ";
}
}
according to me output should be 2 3 4 6 9
but on my machine output is 2 3 4 6 9 1,
why there is an extra 1 in the output.
i am using codeblocks ,gcc 4.8.1
Arrays aren't zero-terminated, so the loop while (*x != NULL) will keep reading beyond the array until it finds a zero-valued word, or crashes, or causes some other undefined behaviour.
You'll either need to add a terminator to the array (if you can choose a value, perhaps zero, that won't be a valid array element), or return the length in some other way.
You can use a count and take the size of the array.
Like this:
int k = 0;
while(k <= sizeof(x)){
cout << " "<< *x++;
k++;
}
With std::vector your function will be:
std::vector<int> ptest() {
static const int a[] = {2,3,4,6,9};
std::vector<int> vec (a, a + sizeof(a) / sizeof(a[0]) );
return vec;
}