This question already has answers here:
Initialization of all elements of an array to one default value in C++?
(12 answers)
Closed 3 months ago.
I'm trying to initialize a single value to whole array in c++.
For ex:- I want to initialize 1 in whole array by writing it by only once
I have tried to initializing 1 in whole array but it throws error , I'm expecting 1 in whole array.
ex- int array[5]={0};
output- 0 0 0 0 0
int array[5]={1};
output- 1 0 0 0 0
expecting- 1 1 1 1 1
if you want 1 value at very index you can do this by
int arr[5] = {1,1,1,1,1}; or
int arr[5];
arr[0] = 1;
arr[1] = 1;
arr[2] = 1;
arr[3] = 1;
arr[4] = 1;
otherwise if you write arr[5] = {1}; only first index will have value 1 rest will be assigned zero automatically like this {1,0,0,0,0}
or #include <iostream>
using namespace std;
int main()
{
int arr[5];
memset(arr, 1, sizeof(arr));
cout << arr;
return 0;
}
so type this code this memset function will fill all the index with value 1 by writing it only once.
hope this answer helps you.
Edited, try this code snippet working perfectly fine
#include <iostream>
#include <array>
int main () {
std::array<int,5> myarray;
myarray.fill(1);
std::cout << "myarray contains:";
for ( int& x : myarray) { std::cout << ' ' << x; }
std::cout << '\n';
return 0;
}
Related
I'm new to coding with pointers.
This is my code.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int a = 1;
int* p = &a;
for (int i = 0;i < 10; i++) {
p++;
*(p) = rand() % 10 + 1;
cout << p << " " << *p << endl;
}
}
Somehow, the code keeps ending before the loop end and print out a series of address but then in the last address end with 03. Can anyone help I search all over but nothing.
output:
00000073532FF808 2
00000073532FF80C 8
00000073532FF810 5
00000073532FF814 1
00000073532FF818 10
00000073532FF81C 5
00000073532FF820 9
00000073532FF824 9
0000007300000003
First, there is allocated storage for one int.
int a = 1;
Second a pointer which points to this storage.
int *p = &a;
Now, writing to *p will modify a but...
for (int i = 0;i < 10; i++) {
p++;
*(p) = rand() % 10 + 1;
i.e. p is incremented.
Even in the first loop it now points to memory beyond a.
That memory is either allocated for something else, or used for something else, or not allocated at all.
In any case, this is Undefined Behavior i.e. writing out of bounds.
That's the nature of Undefined Behavior that everything is possible now—no predictions can be made anymore what will happen.
If the loop terminates before 10 iterations are done I suspect that i might be corrupted by this. It's also possible that p corrupts itself. This doesn't change the fact that it's Undefined Behavior.
A possible fix of OPs application would be to provide sufficient storage in a where p can be iterated over without going out-of-bounds.
For this, the definitions at the beginning of main() had to be changed to:
int a[11] = { 1 };
int* p = a; // could also be: int* p = &a[0];
Please, note that p is incremented before writing to it.
Hence, in the last iteration (with i = 9), p will point to a[10] before the write access. Therefore, the minimal sufficient array size is int a[11] instead of int a[10] which someone might think from the first glance.
The fixed program of OP:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int a[11] = { 1 };
int* p = a;
for (int i = 0;i < 10; i++) {
p++;
*(p) = rand() % 10 + 1;
cout << p << " " << *p << endl;
}
// double check
cout << "a:";
for (int value : a) cout << ' ' << value;
cout << endl;
}
Output:
0x7fff57151bc4 4
0x7fff57151bc8 7
0x7fff57151bcc 8
0x7fff57151bd0 6
0x7fff57151bd4 4
0x7fff57151bd8 6
0x7fff57151bdc 7
0x7fff57151be0 3
0x7fff57151be4 10
0x7fff57151be8 2
a: 1 4 7 8 6 4 6 7 3 10 2
Live Demo on coliru
I want to create an array and raise 2 to every element in that array and store it as new array arr2. Here is my code
#include <iostream>
using namespace std;
int main(){
int arr1[7] = {1, 2, 3, 4, 5, 6, 7};
auto arr2 = 2 ** arr1;
cout << arr2 << endl;
}
But, it prints only the first element, it does not print the whole array. Why? So, basicaly, what I did here is I created arr1 with elements {1,2,3,4,5,6,7} and then I want arr2 to be
[2, 4, 8, 16, 32, 64, 128]
but for some reason it prints only the first element of array, it prints 2, but I want it to print all elements. Notice that 2 ** arr1 is the line where I am raising 2 to power (using exponentiation operator, i think it is how you call it if I'm not wrong) and then it should store array at array2.
What is wrong and why does it print only the first element instead all the elements?
** is not an exponentation operator. C++ is not Fortran.
You have multiplied 2 by the first element of arr: your statement is equivalent to int arr2 = 2 * arr1[0];. What you have entered is perfectly legal C++ (consisting of multiplication and pointer dereference), and the use of auto is adding to the obfuscation.
This statement
auto arr2 = 2 ** arr1;
is equivalent to
auto arr2 = 2 * *arr1;
Array designators in expressions are converted (with rare exceptions) to pointers to their first elements.
So the above statement can be rewritten like
auto arr2 = 2 * *( &arr1[0] );
As the first element of the array arr1 is equal to 1 then you have
auto arr2 = 2 * 1;
The expression 2 * 1 has the type int.
So as result the statement can be just rewritten like
int arr2 = 2;
There is no such operator as ** in C++. Instead you have to use standard function pow.
You can do the task either by writing an appropriate loop manually or using for example the standard algorithm std::transform.
Here is a demonstrative program
#include <iostream>
#include <cmath>
#include <algorithm>
#include <iterator>
int main()
{
int arr1[] = { 1, 2, 3, 4, 5, 6, 7 };
int arr2[sizeof( arr1 ) / sizeof( *arr1 )];
std::transform(std::begin(arr1), std::end(arr1),
std::begin(arr2),
[](int x) { return pow( 2, x ); });
for (int x : arr1) std::cout << x << ' ';
std::cout << std::endl;
for (int x : arr2) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
Its output is
1 2 3 4 5 6 7
2 4 8 16 32 64 128
The simplest way to do what you want can be something like this.
#include<iostream>
#include<math.h>
using namespace std;
int main(){
int arr1[7] = {1,2,3,4,5,6,7}, arr2[7];
for(int i = 0; i<7; i++){
arr2[i] = pow(2, arr1[i]); //arr2 will be created.
cout<<arr2[i]<<" "; //Show arr2.
}
}
In my main() function I have declared an array of type int with the numbers 1 to 10. I then have two other functions of type int* that take this array and its size as parameters, perform some operations, and each returns a pointer to the new array. Where I'm having issues is with a third function that prints the contents of the array.
#include <iostream>
using namespace std;
const int SIZE_OF_ARRAY = 10;
int main() {
int array[SIZE_OF_ARRAY] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *ptr1 = 0;
ptr1 = function1(array, SIZE_OF_ARRAY);
print(array, SIZE_OF_ARRAY);
cout << endl;
int *ptr2 = 0;
ptr2 = function2(array, SIZE_OF_ARRAY);
print(array, SIZE_OF_ARRAY);
return 0;
}
void print(int array[], const int SIZE_OF_ARRAY)
{
for (int i = 0; i < (SIZE_OF_ARRAY * 2); i++)
{
cout << array[i] << " ";
}
}
int* function1(int array[], const int SIZE_OF_ARRAY)
{
int *ptr = new int[SIZE_OF_ARRAY];
// Do stuff.
return ptr;
}
int* function2(int array[], const int SIZE_OF_ARRAY)
{
int *ptr2 = new int[SIZE_OF_ARRAY * 2];
// Create new array double in size, and set contents of ptr2
// to the contents of array. Then initialize the rest to 0.
return ptr2;
}
As expected here, the result of calling the print() function twice is something like:
1 2 3 4 5 6 7 8 9 10 465738691 -989855001 1483324368 32767 -1944382035 32767 0 0 1 0
1 2 3 4 5 6 7 8 9 10 465738691 -989855001 1483324368 32767 -1944382035 32767 0 0 1 0
But I want the result to be like this instead:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 0 0 0 0 0 0 0 0 0 0
How can I accomplish this? (Note that for this assignment I'm using C++98). Thanks in advance.
new int[SIZE_OF_ARRAY] allocates memory, but doesn't assign values to the array elements. What you are seeing is what was in that memory when it got allocated for the array. You can change your function2 to assign zeroes to array elements, if that's what you want.
First of all, you want to print different number of elements on the two calls to print, so you should not delegate deciding whether to multiply the size by two to the print, but rather do it on the calling side. Change the print function to only iterate up to SIZE_OF_ARRAY, and change the two places where you call it to:
print(ptr1, SIZE_OF_ARRAY);
and
print(ptr2, SIZE_OF_ARRAY * 2);
correspondingly.
Now, I assume that your second function does assign values to all 20 elements, but if it does not, the ones to which it did not assign values would continue containing garbage. To get around it, just initialize them at the beginning of the second function:
int *ptr2 = new int[SIZE_OF_ARRAY * 2];
for (size_t i = 0; i < SIZE_OF_ARRAY * 2; ++ i) ptr2[i] = 0;
With these two changes you should get the desired behavior.
Also, if you allocate something with new[], you need to delete it with delete[], otherwise you get a memory leak. Add these two lines at the end of main:
delete[] ptr1;
delete[] ptr2;
Note, that using delete instead of delete[] would be wrong in this case. If something is allocated as an array, it must be deleted as an array.
I'm trying to make a recursive program that sums an array or a list of numbers.
Using visual studio 2013, C++ console application.
My 1st question is:
Now I know how many numbers I have and I know the size of my array. How can I program it the way that don't know the numbers in advance, like while it's calculating the numbers there are still new numbers adding up, with the least space usage?
My 2nd question is that:
How can i improve the program that still works recursively and its time and space usage be optimal?
Here is my code:
// summing a list of number.cpp
#include "stdafx.h"
#include "iostream"
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0, i = 0;
int sumarray(int i){
if (i < 9){
sum += array[i];
i++;
sumarray(i);
}
else
return sum;
}
int main(){
std::cout << "sum is ::: " << sumarray(i);
getchar();
}
I hope you'll stop writing functions that depend on global variables to work when they can be easily made to work only with the input they have been provided.
Here's a version that works for me.
#include <iostream>
int sumarray(int array[], int i)
{
if ( i <= 0 )
{
return 0;
}
return sumarray(array, i-1) + array[i-1];
}
int main()
{
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::cout << "sum is : " << sumarray(array, 0) << std::endl;
std::cout << "sum is : " << sumarray(array, 5) << std::endl;
std::cout << "sum is : " << sumarray(array, 10) << std::endl;
}
Output:
sum is : 0
sum is : 15
sum is : 55
If i >= 9, your function does a return sum;.
(that is fine and good)
Where does your function return if i < 9???
if (i < 9){
sum += array[i];
i++;
sumarray(i); // I see no return statement here!!
}
Basically, if you call sumarray(3), there is no return statement that gets hit.
In your program, there is a global variable called i.
There is also a local parameter to the function also called i.
The local variable shadows the global variable, so there is no clear purpose to the global i.
I'd do it like this:
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Pass in the current index, and the size of the array
int sumarray(int i, int sz)
{
if (sz == 0)
{
return 0;
}
return array[i] + sumarray(i+1, sz-1);
}
int main(){
std::cout << "sum is ::: " << sumarray(0, 10);
// Start at the beginning (index 0)
// Run for 10 elements.
getchar();
}
The first recursive call will be to sumarray(1,9); then to sumarray(2,8);... when finally sumarray(10,0) is called, it will return 0.
A function to sum the elements of an array would normally accept the array as an argument. In that case, as a practical matter it must also accept the size of the array. Something like this:
int sumarray(int a[], size_t size) {
A signature like that furthermore gives you access to better recursive approaches. In particular, you could recursively compute the sum of the first and second halves of the array, and return their sum:
size_t midpoint = size / 2;
return sumarray(a, midpoint) + summaray(a + midpoint, size - midpoint);
That's not a complete solution: you need a termination condition (when size is less than 2). Putting that in and finishing off the function are left as an exercise for you, since you'll learn better if you have to put some work into it yourself.
That approach limits the recursion depth and thus stack size (memory overhead) to be proportional to the logarithm of the array size, though it still involves total numbers of function calls and integer additions proportional to the array size. I don't think you can achieve better asymptotic space or time complexity with a recursive algorithm. (A non-recursive algorithm for this task requires only a fixed number of function calls and and a fixed amount of memory overhead, however.)
here is a working C++ code in Qt, which i wrote - Good Luck
I added some debug points outputs to make its understanding clearer
#include <QCoreApplication>
#include <QDebug>
int sum=0;
int sumrec(int *array,int n)
{
if (n>=0)
{
int element=*(array+n); // note *(array+n) -> moving the pointer
// *array+n -> this is adding n to the pointer data (wrong)
// what is array ?
qDebug() << " element value " << *(array+n) << " at n=" << n << " array address = " << array;
n--;
sum=sum+element;
qDebug() << "sum = " << sum;
sumrec(array,n);
return sum;
}
else
{
return 0;
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int A[10]={12,13,14,15,16,17,18,19,20,11};
int b=sumrec(&A[0],9);
qDebug() << "answer = " << b;
//return a.exec();
}
here is the output of the terminal
element value 11 at n= 9 array address = 0x7fff5fbffb78
sum = 11
element value 20 at n= 8 array address = 0x7fff5fbffb78
sum = 31
element value 19 at n= 7 array address = 0x7fff5fbffb78
sum = 50
element value 18 at n= 6 array address = 0x7fff5fbffb78
sum = 68
element value 17 at n= 5 array address = 0x7fff5fbffb78
sum = 85
element value 16 at n= 4 array address = 0x7fff5fbffb78
sum = 101
element value 15 at n= 3 array address = 0x7fff5fbffb78
sum = 116
element value 14 at n= 2 array address = 0x7fff5fbffb78
sum = 130
element value 13 at n= 1 array address = 0x7fff5fbffb78
sum = 143
element value 12 at n= 0 array address = 0x7fff5fbffb78
sum = 155
answer = 155
In C++ you have all the tools to do that in a very simple, readable and safe way. Check out the valarray container:
#include <iostream>
#include <valarray>
int main () {
std::valarray<int> array{1,2,3,4,5,6,7,8,9,10};
std::cout << array.sum() << '\n';
return 0;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C and C++ : Partial initialization of automatic structure
While reading Code Complete, I came across an C++ array initialization example:
float studentGrades[ MAX_STUDENTS ] = { 0.0 };
I did not know C++ could initialize the entire array, so I've tested it:
#include <iostream>
using namespace std;
int main() {
const int MAX_STUDENTS=4;
float studentGrades[ MAX_STUDENTS ] = { 0.0 };
for (int i=0; i<MAX_STUDENTS; i++) {
cout << i << " " << studentGrades[i] << '\n';
}
return 0;
}
The program gave the expected results:
0 0
1 0
2 0
3 0
But changing the initialization value from 0.0 to, say, 9.9:
float studentGrades[ MAX_STUDENTS ] = { 9.9 };
Gave the interesting result:
0 9.9
1 0
2 0
3 0
Does the initialization declaration set only the first element in the array?
You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,
float arr1[10] = { }; // all elements are 0
float arr2[10] = { 0 }; // all elements are 0
float arr3[10] = { 1 }; // first element is 1, all others are 0
float arr4[10] = { 1, 2 }; // first element is 1, second is 2, all others are 0
No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.