How in input an array of integers by pointers and print out the array and the size of the array(C++) - c++

#include<iostream>
using namespace std;
int main() {
int *p=new int [10];
}
After creating the array, I am confused and want to know if it's possible to do the following:
read an array of integers without builtin arrays such as vector.
print out this array.
Is there any built-in command that we can use in cpp to get the actual size of the array, which means we don't have to use sizeof(*p)/size(p[0]).
And what do you think will be the easiest way of doing this task, on the condition that we still use the pointer of an array.
Thanks for helping me out!

I think you could use std::for_each. Together with c++ lambda functions it is a very comprehensive tool:
for_each(p, p+10, []->(int element){ cout << element; })
sry, I didn't compile the code above, so it might contain errors. But the pattern is clear, I hope.
If your compiler does not support lambdas, you can use functors or function pointers (just google for it). I really like this approach and I don't like loops either.
But, of course as mentioned above, internally the for_each loops.

This does not create an array, but it gives you a pointer to a single integer.
int *p=new int;
change this for example to:
const unsigned size = 10;
int * p = new int[size]; /*dont forget to call delete[] on p when you are ready.*/
Now p points to 10 ints, you know the size since you've put size to 10.
Sure you can print the values of p without a loop
/*Assuming you initialize the values.*/
cout << p[0];
cout << p[1];
/*etc*/
cout << p[9];
That said I think the easiest way to solve your problem is to use vector<int> ( but this doesn't satisfy you first point ). You'll always get the proper size of a vector with vector<TYPE>::size() and a intance of vector makes it easy to iterate ( which is also looping ) over the items to print them.

You would have to print the array manually one item by one... accessing every value, like:
cout << "index 5:" << p[5] << endl;
I think that the loop is a way to go. I would avoid a loop only if the array had few items, and fixed length like 3 to 5 items or so and desperately needed to optimize the code for speed, but not with console output which will be slow anyway. But the compilers usualy support loop unrolling optimalisations.
#nio, but dude, I think I still have trouble of doing this. for example, is there any way that I can input in this simple way "1 2 3 4" with space and then it reads the array? or I have to do it with enter? (Now, I don't care if we use loop or not any more :P) – Cancan
This code will read 4 items separated by combination of spaces and newlines:
int *p=new int[10];
int i;
for(i=0;i<4;i++)
{
cin >> p[i];
}
for(i=0;i<4;i++)
{
cout << "index " << i << " :" << p[i] << endl;
}

1. read an array of integers without using loops nor some builtin arrays such as vector.
Recursion. Everything that can be done using loops can be done recursively.
2. print out this array without using loop.
Recursion too.
3. Is there any built-in command that we can use in cpp to get the actual size of the array, which means we don't have to use sizeof(*p)/size(p[0]).
No, when you're using arrays in c++ you need to remember the length of an arrays by yourself. sizeof(*p)/size(p[0]) won't help you too

Related

Printing a Pointer Vector's Value

Say I have a vector of pointers, but I want to print out the value that the first pointer points to. What syntax would I use? I'm learning to work with pointers and I can't find this specific case anywhere on google myself.
Ex:
vector<int*> vec;
//fill the vector however it needs to be
cout << vec[0];
//This prints an address but I want the value that address points to
You can get the value of what a pointer is pointing at by dereferencing the pointer with *, so you'd get *(vec[0]), this would require the vector to at least have one element in the first place and point to something valid of course.
That being said, please reconsider if you actually need to use pointers at all, a lot of the time I see pointers being used without a good reason. Use normal ints if you don't have a good reason to justify using pointers.
You just have to dereference the pointer you obtain with vec[0], i.e. you'd have to write
cout << *(vec[0]) << endl;
Note, however, that you did not reserve memory for the pointer; probably you even want to manage plain arrays of ints.
A working (even if one still may discuss how meaningful it is to have a vector maintaining pointers to ints) example could look as follows:
int main() {
int a[] = { 1,2,3 };
std::vector<int*> vec;
vec.push_back(a);
cout << *(vec[0]) << endl;
cout << vec[0][1] << endl;
}
Output:
1
2

Pass array to function without so it would not change original array no matter what

I have a function that performs some magic on the array that I am passing. But the original array should be intact. Unfortunately it is changing its content based on what is happening in the array.
Can you help me, please?
Function:
void test(int* array) {
array[0] = 1; // EDIT: Added missing line
std::cout << "Inside: " << array[0] << endl;
}
int main() {
int *testArray = new int[1];
testArray[0] = 0;
std::cout<<testArray[0]<<endl;
test(testArray);
std::cout << "Outside: " << testArray[0] << endl;
}
Current result is:
0
Inside: 1
Outside: 1
Result I would want to have:
0
Inside: 1
Outside: 0
Is this possible?
It sounds like you want to pass array by value not by reference. You are passing pointer to a first element here. So, any changes which you perform to that array inside that function will be reflected to original array.
The other problem is you haven't posted fair amount of code regarding the problem you want to solve. I am assuming you want functionality like this.
See live demo here.
#include <iostream>
void test(const int* array) {
array[0]=1;
std::cout << "Inside: " << array[0] << std::endl;
}
int main() {
int *testArray = new int[1];
testArray[0] = 0;
std::cout<<testArray[0]<<std::endl;
test(testArray);
std::cout << "Outside: " << testArray[0] << std::endl;
delete[] testArray;
}
Compiler will give you following errors:
Error(s):
source_file.cpp:4:13: error: read-only variable is not assignable
array[0]=1;
~~~~~~~~^
1 error generated.
You should not use new[] to allocate dynamic arrays in C++. 99% of the time you should be using std::vector If you want dynamic array in C++.
Avoid using C compatibility features...
void test( std::array<int, 1> a )
{
a[0] = 1; // fine
std::cout << "Inside: " << a[0] << endl;
};
int main()
{
std::array<int, 1> testArray;
testArray[0] = 0;
std::cout<<testArray[0]<<endl;
test(testArray);
std::cout << "Outside: " << testArray[0] << endl;
}
If you need the size determined at runtime, use std::vector instead of std::array.
EDIT: As others have pointed out, it seems like you want to either pass the array by value instead of by reference, thus copying the elements of the array and modifying only the copy, or you want to avoid modifying any part of the array altogether. I'll elaborate on both parts a bit more:
In C++, there is near to no distinction between arrays and pointers. Note that both your variable testArray and your parameter array are pointers to the beginning of an array. If you use array to modify any part of the underlying array, what you actually do is modify the memory are that is described by both testArray and array. If you don't want to modify any part of the array at all, it would be helpful to use the const qualifier, as Destructor already wrote in his answer. If you however want to keep the original array but still want to make some modifications inside the function, the following still applies:
To keep the array from being modified, the only general way that works is to copy all of its elements by creating a new array of the same size, copying all elements from the input array to the copy and then working only on the copy, which should be deleted after the function has finished.
My personal answer:
I would recommend that you look into some of C++'s data structures, especially std::vector. If you pass it by value (not by reference), vector takes care of all the necessary copy operations I just described and in all cases, you can use it in the same way as an array, while it provides lots of additional features (i.e. dynamic size, deletion and insertion of elements, simplified iteration, ...).

generate multidimensinal array instead of cout

I have this main function and i want to get an multidimensional array out of this to generate a graph instead of cout
int main(){
zoro z;
std:ifstream k("ggg.grf");
z.getfromstream(k);
for(int i =0 ; i < z.nnodes; i++){
edge_iteratore s = z.begin(i);
while(s != z.end(i)){
std:cout << "(" << (*s).height << "," << (*s).weight << ")" << std::endl;
++s;
}
}
return 0;
}
I' trying to get std::out to a function to generate a multidimensional array
so i have implemented this function to get an array,
int createarr(height,width){
int** ary = new int*[height];
for(int i = 0; i < height; ++i)
ary[i] = new int[weight];
}
but nothing works, how can i return an multidimensional array to use it in another function call instead of outputting it to the screen.
If height and weight are constexpr values you know at compile time, declare std::array<<std::array<int>, weight>, height>. This gets you locality of reference. If they are values you compute at runtime or that could vary, use vector<vector<int>>(height) and initialize each row. Then the compiler takes care of freeing the memory for you. If only one is fixed, you can also do a vector of arrays or an array of vectors.
It’s unfortunate that, because of the legacy char** argv interface of main(), every beginning C and C++ programmer thinks that’s how you do a two-dimensional array. A ragged array like that is almost never what you really want. But if you do, use std::vector to manage the memory for you.
The problem with your createarr() as written is that it doesn’t return any array pointer, but RAII is more likely what you want. And if you do have a sparse matrix that would benefit from raggedness, you can use a format like Compressed Sparse Row.
You need to return a pointer to the created array.
But you'll need to somehow deal with the fact that this is dynamically allocated memory, ie, you need to release it when you're done.
And you'll need to somehow encapsulate the dimensions too, which then means it needs to be a struct.
When you finally get tired of dealing with memory leaks, and understand how pointers work, use std::vector like the other guy said.
In the meantime, don't try to implement complicated algorithms in C without understanding the basics first. Brush up hard on how pointers and arrays actually work, first.

Can I determine the size/length of an array in C++ without having to hardcode it?

I am basically looking for some sort of "dynamic" way of passing the size/length of an array to a function.
I have tried:
void printArray(int arrayName[])
{
for(int i = 0 ; i < sizeof(arrayName); ++i)
{
cout << arrayName[i] << ' ';
}
}
But I realized it only considers its bytesize and not how many elements are on the array.
And also:
void printArray(int *arrayName)
{
while (*arrayName)
{
cout << *arrayName << ' ';
*arrayName++;
}
}
This has at least printed me everything but more than what I expected, so it doesn't actually work how I want it to.
I reckon it is because I don't exactly tell it how big I need it to be so it plays it "safe" and throws me some big size and eventually starts printing me very odd integers after my last element in the array.
So I finally got this work around, yet I believe there is something better out there!:
void printArray(int *arrayName)
{
while (*arrayName)
{
if (*arrayName == -858993460)
{
break;
}
cout << *arrayName << ' ';
*arrayName++;
}
cout << '\n';
}
After running the program a few times I realized the value after the last element of the array that I have input is always: -858993460, so I made it break the while loop once this value is encountered.
include <iostream>
include <conio.h>
using namespace std;
// functions prototypes
void printArray (int arrayName[], int lengthArray);
// global variables
//main
int main ()
{
int firstArray[] = {5, 10, 15};
int secondArray[] = {2, 4, 6, 8, 10};
printArray (firstArray,3);
printArray (secondArray,5);
// end of program
_getch();
return 0;
}
// functions definitions
void printArray(int arrayName[], int lengthArray)
{
for (int i=0; i<lengthArray; i++)
{
cout << arrayName[i] << " ";
}
cout << "\n";
}
Thank you very much.
TL;DR answer: use std::vector.
But I realized it [sizeof()] only considers its bytesize and not how many elements are on the array.
That wouldn't be a problem in itself: you could still get the size of the array using sizeof(array) / sizeof(array[0]), but the problem is that when passed to a function, arrays decay into a pointer to their first element, so all you can get is sizeof(T *) (T being the type of an element in the array).
About *arrayName++:
This has at least printed me everything but more than what I expected
I don't even understand what inspired you to calculate the size of the array in this way. All that this code does is incrementing the first object in the array until it's zero.
After running the program a few times I realized the value after the last element of the array that I have input is always: -858993460
That's a terrible assumption and it also relies on undefined behavior. You can't really be sure what's in the memory after the first element of your array, you should not even be accessing it.
Basically, in C++, if you want to know the size of a raw array from within a function, then you have to keep track of it manually (e. g. adding an extra size_t size argument), because of the way arrays are passed to functions (remember, they "decay into" a pointer). If you want something more flexible, consider using std::vector<int> (or whatever type of objects you want to store) from the C++ standard library -- it has a size() method, which does exactly what you want.
1st try
When arrays are passed into functions they decay to pointers. Normally, using sizeof on an array would give you its size in bytes which you could then divide by the size in bytes of each element and get the number of elements. But now, since you have a pointer instead of an array, calling sizeof just gives you the size of the pointer (usually 4 or 8 bytes), not the array itself and that's why this fails.
2nd try
The while loop in this example assumes that your array ends with a zero and that's very bad (unless you really did use a zero as a terminator like null-terminated strings for example do). If your array doesn't end with a zero you might be accessing memory that isn't yours and therefore invoking undefined behavior. Another thing that could happen is that your array has a zero element in the middle which would then only print the first few elements.
3rd try
This special value you found lurking at the end of your array can change any time. This value just happened to be there at this point and it might be different another time so hardcoding it like this is very dangerous because again, you could end up accessing memory that isn't yours.
Your final code
This code is correct and passing the length of the array along with the array itself is something commonly done (especially in APIs written in C). This code shouldn't cause any problems as long as you don't pass a length that's actually bigger than the real length of the array and this can happen sometimes so it is also error prone.
Another solution
Another solution would be to use std::vector, a container which along with keeping track of its size, also allows you to add as many elements as you want, i.e. the size doesn't need to be known at runtime. So you could do something like this:
#include <iostream>
#include <vector>
#include <cstddef>
void print_vec(const std::vector<int>& v)
{
std::size_t len = v.size();
for (std::size_t i = 0; i < len; ++i)
{
std::cout << v[i] << std::endl;
}
}
int main()
{
std::vector<int> elements;
elements.push_back(5);
elements.push_back(4);
elements.push_back(3);
elements.push_back(2);
elements.push_back(1);
print_vec(elements);
return 0;
}
Useful links worth checking out
Undefined behavior: Undefined, unspecified and implementation-defined behavior
Array decay: What is array decaying?
std::vector: http://en.cppreference.com/w/cpp/container/vector
As all the other answers say, you should use std::vector or, as you already did, pass the number of elements of the array to the printing function.
Another way to do is is by putting a sentinel element (a value you are sure it won't be inside the array) at the end of the array. In the printing function you then cycle through the elements and when you find the sentinel you stop.
A possible solution: you can use a template to deduce the array length:
template <typename T, int N>
int array_length(T (&array)[N]) {
return N;
}
Note that you have to do this before the array decays to a pointer, but you can use the technique directly or in a wrapper.
For example, if you don't mind rolling your own array wrapper:
template <typename T>
struct array {
T *a_;
int n_;
template <int N> array(T (&a)[N]) : a_(a), n_(N) {}
};
You can do this:
void printArray(array<int> a)
{
for (int i = 0 ; i < a.n_; ++i)
cout << a.a_[i] << ' ';
}
and call it like
int firstArray[] = {5, 10, 15};
int secondArray[] = {2, 4, 6, 8, 10};
printArray (firstArray);
printArray (secondArray);
The key is that the templated constructor isn't explicit so your array can be converted to an instance, capturing the size, before decaying to a pointer.
NB. The wrapper shown isn't suitable for owning dynamically-sized arrays, only for handling statically-sized arrays conveniently. It's also missing various operators and a default constructor, for brevity. In general, prefer std::vector or std::array instead for general use.
... OP's own attempts are completely addressed elsewhere ...
Using the -858993460 value is highly unreliable and, in fact, incorrect.
You can pass a length of array in two ways: pass an additional parameter (say size_t length) to your function, or put a special value to the end of array. The first way is preferred, but the second is used, for example, for passing strings by char*.
In C/C++ it's not possible to know the size of an array at runtime. You might consider using an std::vector class if you need that, and it has other advantages as well.
When you pass the length of the array to printArray, you can use sizeof(array) / sizeof(array[0]), which is to say the size in bytes of the whole array divided by the size in bytes of a single element gives you the size in elements of the array itself.
More to the point, in C++ you may find it to your advantage to learn about std::vector and std::array and prefer these over raw arrays—unless of course you’re doing a homework assignment that requires you to learn about raw arrays. The size() member function will give you the number of elements in a vector.
In C/C++, native arrays degrade to pointers as soon as they are passed to functions. As such, the "length" parameter has to be passed as a parameter for the function.
C++ offers the std::vector collection class. Make sure when you pass it to a function, you pass it by reference or by pointer (to avoid making a copy of the array as it's passed).
#include <vector>
#include <string>
void printArray(std::vector<std::string> &arrayName)
{
size_t length = arrayName.size();
for(size_t i = 0 ; i < length; ++i)
{
cout << arrayName[i] << ' ';
}
}
int main()
{
std::vector<std::string> arrayOfNames;
arrayOfNames.push_back(std::string("Stack"));
arrayOfNames.push_back(std::string("Overflow"));
printArray(arrayOfNames);
...
}

c++ creating a subarray from a duplicate array

here is my code and im not allowed to use a loop in the subarray function im pretty confused maybe someone can point me in the right direction i feel like im almost there..
int *duplicateArray(int *arr, int size)
{
int *newArray;
if (size<=0)
return NULL;
newArray = new int[size];
for (int index=0;index<size;index++)
newArray[index]=arr[index];
return newArray;
}
int* subArray(int *sub, int start, int length)
{
int aa[10]={1,2,3,4,5,6,7,8,9,10};
int *dup;
dup = aa;
duplicateArray(dup,10);
return dup;
}
int main()
{ cout << "Testing subArray: " << endl
<< "Expected result: 5, 6, 7, 8 " << endl;
int *subArr;
int start = 5;
subArr = subArray(subArr, 5,4);
for (int index = start; index<10; index++)
cout << subArr[index];
delete [] subArr;
subArr = 0;
So, since this is homework, I'm going to avoid posting a solution directly. You say that;
im not allowed to use a loop in the subarray function
Yet, currently, subArray calls duplicateArray, which uses a loop. This seems to be in conflict with the spirit of the requirement.
Since you haven't said otherwise, I'm assuming that subArray should duplicate the contents of its argument between start and the end. So, what do we know?
We know that the size of the returned array should be length - start elements. We also know (well, perhaps) that a function named memcpy exists which allows you to copy a block of bytes from one place to another (assuming they do not overlap).
(note that I am suggesting memcpy here because we are dealing with POD types (Plain Old Data) and because I doubt your class has delved into the STL. In the future you will be better served by something like std::copy(), but for now this is ok)
So, in order, we need to:
Declare a new array to return with length - start elements. You must dynamically allocate this array! Currently you are returning a pointer to a locally declared array. That pointer becomes invalid as soon as the function returns.
Copy length - start elements (elements, not bytes! Make sure to take into account the number of elements as well as the size of an individual element) from sub + start into this new array.
Return the new array (pointer really).
If I have somehow violated the requirements or intent of your assignment then you need to elaborate on your problem for me. Currently there is not much to go on.