Data type clash [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
#include <iostream>
#include <iomanip>
using namespace std;
void reverseOrder (double []);
int main() {
const int size = 4;
double array[size] = {1.2, 6.7, -12.45, 34.9};
cout << "Forwards:" << " " << endl;
for (int index = 0; index < size; index++) {
cout << array[index] << endl;
}
// Display in reversed order.
cout << "Backwards: " << endl;
reverseOrder(array[size]);
return 0;
}
void reverseOrder(double array[]) {
const int size = 10;
int j;
double reverseOrder[size];
double temp = 0;
for (int i = 0, j = size - 1; i < (size / 2); i++, j--) {
temp = reverseOrder[i];
reverseOrder[i] = array[j];
reverseOrder[j] = temp;
}
for (int reverse = 0; reverse < size; reverse++) {
cout << array[reverse] << endl;
}
}
error C2664: 'void reverseOrder(double [])' : cannot convert argument 1 from 'double' to 'double []'
error is here ---> reverseOrder(array[size]);

You are calling your function reverseOrder(double[]) with array[size] as argument which is only one element of the array(*). So you are passing a double but the function expects an array.
In your case you should call the function with reverseOrder(array).
(*)in this case it is not even an element because it points to the element after the last one because the first element is accessed by 0 and so by 4 you would actually access the 5th element (thanks to drescherjm for pointing that out)

Your particular problem (just the first one from what we can observe) is that you are trying to pass a single double to a function expecting the array of doubles. It is because
array[index]
returns a value of the array associated with given index (you should call this like reverseOrder(array);). That is, it returns this as long as the index is in the allowed range. This is not the case here, because array[size] is one past the last element of the array. The last one is indexed array[size-1]. Thus you are experiencing undefined behavior.

Related

Need to find 3 small errors - memory bugs [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
As part of a college assignment, we were tasked with analyzing some code in an effort to identify memory issues. There's 3 we are to find. As I am quite new to the concept of pointers, I am drawing a blank. I do know main() should be returning an int and that the use of the "unsigned" means non-negative integers in this case.
Compiler Errors
Tried searching for similar problems.
void main()
{
double* d = new double;
for (unsigned int i = 0; i < 3; i++) {
d[i] = 1.5 + i;
}
for (unsigned int i = 2; i >= 0; i--) {
cout << d[i] << endl;
}
}
The program results in an infinite loop of memory addresses.
the first problem is the return type of the main function
the second one is in:
double* d = new double;
you are allocating memory for one double but in your loops, you are accessing to 3 indexes
and last
for (unsigned int i = 2; i >= 0; i--)
the unsigned type can't hold negative value and so after it gets to zero it going up again to max unsigned int (x^32)-1 and you again accessing out of range places
so your code should look like that:
#include <iostream>
int main()
{
double* d = new double[3];
for (unsigned int i = 0; i < 3; i++) {
d[i] = 1.5 + i;
}
for ( int i = 2; i >= 0; i--) {
std::cout << d[i] << std::endl;
}
delete[] d;
return 0;
}
In this statement you are creating memory in heap only for one double variable. If you need 3 . Then you must allocate memory for 3 variable like.
double* d = new double[3];
And the reason loop is infinite is because in second loop when value of i will go to -1 since the variable is unsigned it will get converted to very large positive number depending on your machine like in my machine
it get converted to 4294967295.
unsigned int i = -1;
cout<<i; //try running this code and you will see value of i to be 4294967295
Error explanation
See your 3rd and 2nd last error say the same that value is converted to very large int.
Other error said as i explained above that you have allocated memory for 1 double ie 8byte but you are using it for 3 double (d[1],d[3],d[3]) which is 8 x 3 = 24 bytes.
Remaining is return type which must be int not void

C++ unable to index an element of an array using a nested loop [duplicate]

This question already has answers here:
Split an Integer into its digits c++
(12 answers)
Closed 3 years ago.
I am having difficulty understanding how i can fix this this error "array1[i][j] = expression must be a pointer-to-object type. I have searched the error but i am unable to apply the solutions to my code snippet.
int main(){
int array1[]= {1234,4321}; //{1234,4321};
int array2[]= {2345,3214}; //{2345,3214};
int counter = 0;
int arr_element = sizeof(array1);
int arr_index = sizeof(array1)/sizeof(*array1);
for(int i = 0, count1 = arr_index; i < count1; i++ ){
for(int j = 0, count2 = 4; j < count2; j++){
cout << array1[i][j] << endl;
}
}
return 0;
}
What i would like to do is be able to print out the elements in array1; for example, i would like this output: 1,2,3,4,4,3,2,1. From my understanding, the int a needs to be a pointer. I i added * in front of the array (*array1) and in front of the int (int**), but with no luck. Thank you for your time.
Ypu are using one dimensional array, What you are wishing for is a 2dimensional array and that's how you declare it
int array1[][]= {{1,2,3,4},{4,3,2,1}};
int array2[][]= {{2,3,4,5},{3,2,1,4}};

Invalid conversion error when trying to keep array from changing when called by a function

For this assignment, I need to make a sorted copy of an array the user has given values to. All of my code works as intended, except for this specific part. I need this function (sortedCopy) to print out the sorted version of their array, without actually changing the array itself. As far as I can tell, to do so I need to used a constant version of the array in the function so the prototype would be something like: int *sortedCopy(const int *array, int size), but all this does is give the error shown in the title. Specifically:
main.cpp:72:29: error: assignment of read-only location '*(array +
((sizetype)(((long unsigned int)i) * 4)))' array[i] = array[min]
and it does this error twice, except with array[min] = temp; at the end instead
This is the code used, with the relevant parts of main:
#include <iostream>
using namespace std;
int* sortedCopy(const int *array, int size) {
int i, j, min, temp;
for (i = 0 ; i < size - 1; i++) {
min = i;
for (j = i + 1; j < size; j++) {
if (array[j] < array[min]) {
min = j;
}
}
temp = array[i];
array[i] = array[min];
array[min] = temp;
}
cout << "Sorted array is: " << endl;
for(int i = 0; i < size; i++) {
cout << array[i] << " ";
}
cout << endl;
// Not sure if I need to return anything or not either
}
int main() {
cout << "Please enter the size of the array." << endl;
int arraySize;
int array[arraySize];
cin >> arraySize;
cout << "Please enter integer values until the array is filled." << endl;
for (int i = 0; i != arraySize; i++) {
cout << "Value " << (i + 1) << ": ";
cin >> array[i];
cout << endl;
sortedCopy(array, arraySize);
for (int i = 0; i != arraySize; i++) { // I want this part to print the
cout << array[i] << " "; // original array entered by the user
}
}
If I remove the const part of the function, it works totally fine, except it will print the sorted array after the function is called, instead of the original array.
Firstly, C/C++ is best read "top-down":
int arraySize;
int array[arraySize]; // arraySize is undefined here!!
cin >> arraySize;
On the second line, ArraySize, might be 1, or 0, or -1000. You haven't defined it until line 3.
Also, C++ doesn't allow you to allocate arrays of variable size (unless that size is const [ so it is known at compilation time]):
int array[4];
The above is fine. This helps the operating system know how much memory to provide for you on the stack (it needs to do this before your programme starts running).
const int arraySize = 4;
int array[arraySize];
Because the C++ compiler knows that arraySize is 4, it processes this just like the above code, so this is also fine.
So to handle arrays of genuinely variable length (length that depends on inputs), you need to first read the user inputs, then use dynamic allocation ("new", or a container that does dynamic allocation for you, like a vector).
As for the problem with "const", what I think that you need to understand here is that "const" is really just a promise from the programmer: The programmer is communicating to the compiler (and any programmers reading the code) that this data is not supposed to change. All the compiler does is check whether you keep your promise (or if you send it to another function / pointer that doesn't hold that promise). So by using "const" there is no work done being done for you to actually keep the data constant - just that it will complain if you don't do the work.
int* sortedCopy(const int *array, int size) {
Above you're flagging to the compiler that the sortedCopy function will keep the data in the array constant.
array[i] = array[min];
array[min] = temp;
And here (above) you are breaking that promise.
If you don't want to edit the original array, then the easiest solution is just to copy it before you send it to your sorting function.

Calling a C++ function with an array of arrays [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I've got a library function I need to call and I'm having trouble with c++ basics for some reason.
The declaration of the function is:
void doSomething(int** values, int length, int width);
It's taking an array of integer arrays. This is fine, I'm having trouble sending getting the data into it.
My data is just 2 integers, say 4 & 5.
In c# I think the syntax would be somethings like: [ [4,5] ]
An array containing an array which contains the two values.
How on earth do you declare this basic structure in C++?
I've tried:
int vals[1][2] = { {4,5} };
doSomething(vals, 1,2);
But the compiler comes back with:
error: no matching function for call to ‘myclass::doSomething(int [1][2], int, int)’
doSomething(vals, 1, 2);
^
src/mysclass.cpp:74:6: note: candidate: void myclass::doSomething(int**, int, int)
This must be simple. There must be a simple way to declare this data to call the function with these values. I'd prefer stack based, if possible.
Parameter int **values denotes a pointer to one pointer (or several consecutive pointers) to one int (or several consecutive ints). The "several consecutive..."-case can be used to represent a "two-dimentional array". Note that values points to an array of pointer values, not to an array of ints. This is different from a data structure like int myArr[10][20], where myArr points to / is an array of arrays of integers.
A simple way to call it is to generate a 1D-array, let an int-pointer point to this array, and pass the address of this pointer:
void test (int** value, int length, int width) {
for (int l=0; l<length; l++) {
for (int w=0; w<width; w++) {
cout << "[" << l << "," << w << "]:" << value[l][w] << endl;
}
}
}
int main() {
int myArr[] = { 4,5 };
int* ptrToMyArr = myArr;
test (&ptrToMyArr,1,sizeof(myArr)/sizeof(int));
}
You could also do something like this:
#include <iostream>
void doSomething(int** value, int length, int width)
{
for (int i = 0; i < length; ++i)
for (int j= 0; j < width; ++j)
std::cout << value[i][j] << std::endl;
}
int main()
{
// array of arrays of int
int arr[2][2] = { { 1,2 },{ 3,4 } };
// convert to array of pointers to int
int *vals[2] = { arr[0], arr[1] };
doSomething(vals, 2, 2);
return 0;
}
https://ideone.com/PgpzK0

Array Initialization giving garbage values [duplicate]

This question already has answers here:
Initialization of all elements of an array to one default value in C++?
(12 answers)
Closed 8 years ago.
I want to initialize all the array elements with just one value so I wanted to use option 1, the shorter version. But that does not seem to working. However option 2 works. Can anybody please explain what's going wrong when I try to initialize via option 1..
int main()
{
int arr[5] = { 2 }; // option 1
int arr1[5] = { 2, 2, 2, 2, 2 }; //option 2
for (int i = 0; i < 5; i++)
cout << arr[i] << " ";
for (int i = 0; i < 5; i++)
cout << arr1[i] << " ";
}
int arr[5] = { 2 };
You are providing initial value to first element only. In that case all elements are initialized by default to that type i.e 0 in your case.