Is this function have any sense? if I didn't define the value of p_var1[] and p_size?
Just to know if it make sense, I have bigger code, but as a beginner, for me, if there is no values for these variables, that is weird.
First function:
int max1(int p_values[15][15])
{
int max_value;
for(int i=0; i < 15; i++)
{
int max_v = fnc(p_values[i], 15);
if( max_value < max_v)
{
max_value = max_v;
}
}
return max_value;
}
and second
//p_var1[] - is an array of values
//p_size - is the size of array
int fnc(int p_var1[], int p_size)
{
int max_value;
for (int i = 0; i < p_size; i++)
{
if (max_value > p_var1[i])
{
max_value = p_var[i];
}
}
return max_value;
}
This code isn't a full program, it's just a function definition. Here, a function called fnc is declared that can be called with parameters. Here's an example of a full program using it:
//p_var1[] - is an array of values
//p_size - is the size of array
int fnc(int p_var1[], int p_size)
{
int max_value;
for (int i = 0; i < p_size; i++)
{
if (max_value > p_var1[i])
{
max_value = p_var[i];
}
}
return max_value;
}
int main() {
int lst[5] = {10, 2, 6, 4, 8};
int max = fnc(lst, 5); // max = 10
return 0;
}
I guess you wrote fnc(p_values[i], 15) without knowing what it means? Not the best approach, but asking about it shows promise. When this expression is reached, the fnc identifier says that we're going to pause the execution of the current function (max1) and jump to execute the function fnc. Once that function finishes, the returned value will be the value of the expression and execution of max1 can resume. The stuff in the parentheses says that as we jump to fnc, assign p_var1 = p_values[i] and p_size = 15 (the first parameter is assigned the first argument, and the second parameter is assigned the second argument). If you're confused by the terms "parameter" and "argument", see What's the difference between an argument and a parameter?
So when you call fnc you do define the value of p_var1 and p_size (for that function call). (Wikipedia has an article with an example that covers this also, and you might find some useful information in the rest of that article.)
Related
For some reason, my function LinearSearch is only getting the first element of the array that's being passed in. I found this by putting a breakpoint in the function and looking at the locals that it has, and I don't know why it's only getting the 7 from the array a. The test case I have is the following (GoogleTest):
TEST(LinearSearch, ElementExists2Items) {
// LinearSearch should return a pointer to the item if it exists in the array.
int a[2] = {7, 2};
EXPECT_EQ(a, LinearSearch(a, 2, 7));
EXPECT_EQ(a + 1, LinearSearch(a, 2, 2));
}
Here is my LinearSearch function:
int* LinearSearch(int theArray[], int size, int key) {
if (size == 0)
return nullptr;
for (int i = 0; i < size; i++) {
if (key == theArray[i])
return (theArray);
else
return nullptr;
}
}
Am I missing something? Do I need to pass theArray by reference instead? I don't know why it's only getting the first value passed into the function.
You are returning the very first time.
Solution or rather a hint
for (int i = 0; i < size; i++) {
if (key == theArray[i])
return (theArray);
//if it cannot find it the very first time, it returns null IN YOUR CASE :)
}
return nullptr;
Your Case
Just think about the execution. The very first time it does not find something it immediately returns and exits the function. Hence it only sees one element.
for (int i = 0; i < size; i++) {
if (key == theArray[i])
return (theArray);
else
return nullptr;
}
Update
for (int i = 0; i < size; i++) {
if (key == theArray[i])
return (theArray + i);
// you currently pass the pointer to the start of the array again and again. Pass the pointer to the element instead.
}
return null;
I'm attempting to teach myself the basics of algorithms and data structures through a free online course, and as such, I though it'd give it a first shot at merge sort. This isn't really going to be used for anything so it's pretty sloppy, but I seem to be having a problem where main is not calling the MergeSort function.
The output is 00000000, (I assume because array is never assigned anything). When I run the program through gdb the program seems to get to that line, and then completely skip over the function and go directly to the loop that prints the array.
Any thoughts? Am I missing something stupid?
#include <iostream>
using namespace std;
int *MergeSort(int array[], int sizeOf);
int main(){
int numbers[8] = {5, 4, 1, 8, 7, 2, 6, 3};
int *array = MergeSort(numbers, 8);
for (int i = 0; i < 8; i++)
cout << array[i];
return 0;
}
int *MergeSort(int array[], int sizeOf){
int *leftArr = new int[sizeOf/2]; // Build arrays to split in half
int *rightArr = new int[sizeOf/2];
if (sizeOf < 2){ // Base case to end recursion
return array;
}
else{
for (int i = 0; i < (sizeOf/2); i++){ // Left gets first half
leftArr[i] = array[i];
}
int j = (sizeOf/2) - 1; // Set point to start building 2nd
for (int i = sizeOf; i >= (sizeOf/2); i--){
rightArr[j] = array[i]; // Build other half of array
j--;
}
leftArr = MergeSort(leftArr, sizeOf/2); // Call Recursive functions
rightArr = MergeSort(rightArr, sizeOf/2);
}
static int *newArray = new int[sizeOf]; // Sorted array to Build
int k = 0; // Iterators to build sorted func
int m = 0;
int p = 0;
while (p < sizeOf){
if (leftArr[k] < rightArr[m]){ // Left Arr's current value is less
newArray[p] = leftArr[k]; // right arr's current calue
k++;
}
else if (leftArr[k] >= rightArr[m]){
newArray[p] = rightArr[k];
m++;
}
p++;
}
//for (int i = 0; i < 8; i++)
// cout << newArray[i] << endl;
return newArray; // Return address to new array
}
There is a fundamental design issue in your MergeSort():
your algorithm is recursive (that's perfect)
unfortunately it returns newArraywhich is static. This means that all invocations use the same instance of the same static variable (and overwrite the one returned by the recursive call).
You need to solve this by making newArray non static. And at the end of the function, you need to delete[] the arrays returned by recursive calls in order to avoid memory leakage.
The output for this code is:
9
And I'm not sure what it changes in the function add1. And also what does this &n mean and what does it do when we assign the i to &n?
#include <iostream>
using namespace std;
int add1(int &n){
n++;
return n;
}
int main(){
int m = 0;
for (int i = 0; i < 5; i++){
m += add1(i);
}
cout << m ;
cout << "\n\n";
return 0;
}
When & is used in a parameter list, it will cause that parameter to be passed as a reference to the function.
What this means is that n in your function add1, will point to the same space in memory as i in your main function. Changes to n will also be reflected in i, as they will simply act as different names for the same thing.
Variable i is passed into add1 as a reference parameter, so every round i is increased by two:
1st round: i = 0, m = 1
2nd round: i = 2, m = 4
3rd round: i = 4, m = 9
If you have a function like this
int add1( int n )
^^^^^
{
n++;
return n;
}
and call it like
m += add1(i);
Then the function deals with a copy of the value of vatiable i.
You can imagine it the following way if to build it in the body of the loop
for ( int i = 0; i < 5; i++ )
{
// m += add1(i);
// function add1
int n = i;
n++;
m += n;
}
When a function is declared like this
int add1( int &n )
^^^^^
{
n++;
return n;
}
Then it means that the parameter is a reference to the corresponding original argument. You can consider it just as an alias for the argument.
In this case you can imagine it the following way if to build it in in the body of the loop
for ( int i = 0; i < 5; i++ )
{
// m += add1(i);
// function add1
i++;
m += i;
}
So the variable i is changed twice in the function add1 because it is directly used in the function by means of the reference n and in the control statement of the loop.
Here we are passing a parameter to the add1() function by using pass by reference. To pass a variable by reference, we simply declare the function parameters as references rather than as normal variables.
In above code,
int add1(int &n){ // n is a reference variable
n++;
return n;
}
When the function is called, n will become a reference to the argument. Since a reference to a variable is treated exactly the same as the variable itself, any changes made to the reference are passed through to the argument!
I'm currently trying to write a script so that I can add an item to the last index the array has an item in. For example, if I initialized an array int a[5] and a[0], a[1], a[2] all have something, then the integer would be added to a[3]Here is what I have :
int main(){
int a[5];
a[0] = 10;
a[1] = 20;
a[2] = 30;
for (int i = 0; i < 5; i++){
if (a[i] < 0){
a[i] = 40; //Just an example for what it would be like.
}
}
}
I can't help but feel that there is a better way to do this, maybe a different if condition. I want to know if there's another way to check if the next index is empty.
You could use an array index counter. Say, int counter = 0;
Use the counter as an index when you store integers to the array a, like a[counter] = 5 After you add an integer to your array, increment the counter, counter++.
This way you could make sure that the next value being added to the array is always added the way you described in the question
A few things to probably clear up what looks like a misunderstanding around what an array is:
When you declare an array say
int main()
{
int a[5];
for (int i = 0; i < 5; i++)
{
printf("a[%d] = %d", i, a[i]);
}
}
All elements in the array exist already. Namely, you can access a[0] ... a[4] without hitting an error. All values of the array have already been set implicitly and you can see this by seeing the output of the printf. Note that those are values that you haven't set yourself and will vary. If you're curious about why they vary, you can see this: Variable initialization in C++
To set those values explicitly, you can initialize all values in the array to 0 like so:
int main()
{
int a[5] = {0};
for (int i = 0; i < 5; i++)
{
printf("a[%d] = %d", i, a[i]);
}
}
or through use of a static initializer
int main()
{
int a[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++)
{
printf("a[%d] = %d", i, a[i]);
}
}
However because all values of the array already exist on creation, there isn't really such a state as "uninitialized array" in C++ as they are . The value of a[3] is either set implicitly or explicitly depending on how you created the array.
std::vector is a dynamically growing array, based on how much space you need. In order to have this effect, std::vector keeps track of how much of the array is "used" through use of a size variable. If you wanted to reimplement that to get an idea of how it might be done, you would probably want a class like:
class MyArray
{
public:
MyArray() : m_size(0)
{
}
void AddVal(int data)
{
if (m_size < 5)
{
m_array[m_size++] = data;
}
}
int GetSize()
{
return m_size;
}
private:
int m_array[5];
int m_size;
}
If you initialize the array to 0, you can check if the value is 0.
Initilize:
int array[5] = {0};
Check for 0:
array[4] == 0;
I'm completely new to C++.
Bashing my head against this error for over an hour. Probably someone with experience can see right through it.
The following code gives an error:
class TimeTravellingCellar {
private:
public:
int determineProfit (int [] profit, int [] decay) {
int N = sizeof(profit)/sizeof(decay);
int max = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i == j) continue;
if (profit [i] - decay [j] > max)
max = profit [i] - decay [j];
}
}
return max;
}
}
Visual Studio Express puts a red line under profit in the parameters of determineProfit and says:
expected a ')' before identifier profit.
I will appreciate some help.
Thanks!
You are declaring your arrays as if this were c#. It should be
int profit[]
Or
int *profit
You'll hit this one next. You need to terminate your class with a semi-colon.
class Foo {
}; <----
The next problem you have is logical, not syntactic. This does not do what you think it does:
int N = sizeof(profit)/sizeof(decay);
You are taking the sizeof two pointers, not the size of the arrays. You actually have:
int N = 4/4 /* assumes sizeof int == 4 */
You need to pass in the size of your to the function as well (or, better yet; stop using arrays and use a vector<T>.)
When you take an "array" as an argument to your function it actually decays to a pointer to the array type (an array proper cannot be passed to a function). So it follows that:
void Foo( int array[] ) {
size_t arrSize = sizeof(array);
// arrSize == 4 for a 32-bit system, i.e., sizeof(int*)
int a[100];
size_t actualSizeInBytes = sizeof(a);
// actualSizeInBytes == 400, i.e., 4 * 100 as an int occupies 4 bytes
}
Next, this line causes your first iteration to always be skipped. Not sure if that is intentional:
if (i == j) continue;
You don't declare arrays like that in C++, the [] needs to go after the name.
Also note you need to have a semicolon after the class declaration.
class TimeTravellingCellar {
private:
public:
int determineProfit (int profit[], int decay[]) {
int N = sizeof(profit)/sizeof(decay);
int max = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i == j) continue;
if (profit [i] - decay [j] > max)
max = profit [i] - decay [j];
}
}
return max;
}
};
Edit: also remember that sizeof(pointer) will return the number of bytes of the pointer type, not the number of elements in the array. So if you have an int array, sizeof(array) == sizeof(int). Your N value will always equal 1.
This line is wrong:
int determineProfit (int [] profit, int [] decay) {
Change it into:
int determineProfit (int profit[], int decay[]) {
or
int determineProfit (int* profit, int* decay) {
and add a closing ;
If you do that and add a main, of course:
int main() {}
then you can compile your code - I just tried it with g++.
Try int determineProfit (int* profit, int* decay) because for formal arguments, arrays and pointers are almost alike.
Brackets are associated with the variable name, not the type. The first line should be
int determineProfit (int profit[], int decay[]) {
A tutorial on arrays in C may be enlightening, especially as regards the passing of array parameters.
int determineProfit (int[] profit int [] decay
here is your error - the above statement is wrong; it should be like this
int determineProfit (int profit[], int decay[])