#include<stdio.h>
#include<stdlib.h>
int* getEvenNumbers(int arr[], int N)
{
int i, k = 0 , a[50], p;
for (i = 0; i < N; i++)
{
if (arr[i] % 2 == 0)
{
arr[k]=arr[i];
k++;
}
}
return arr[k];
}
int main ()
{
int i, arr[5000000], N, a[500000], k, *p;
printf("\nEnter your desired length of the array:\n\n");
scanf("%d", &N);
for (i = 0; i < N; i++)
arr[i]= rand();
getEvenNumbers (arr, N);
printf("\n\nEven numbers in the array are as follows:\n\n");
for (i = 0; i < N; i++)
{
a[i]= *(p+i);
printf("\n[%d] = %d", (i+1), a[i]);
}
}
please i know this is probably very easy for you guys but i need help figuring out how to return a pointer to the array without all my values of my array getting deleted, also i can't use global variables and it has to be a function that returns a pointer pointing to the array
First of all, decrease the size of those arrays, you don't need that much space. Second of all, you made your
getEvenNumbers
function return an int *, and not an int. arr[k] is not an int *. I also don't get why you are returning something if nothing is being assigned when you call the function. You can just change the return type to void.
void getEvenNumbers(int arr[], int N)
You also never allocate any memory for p. You can do
p = (int*) malloc(sizeof(int));
And since you never allocated any memory for p, the following line of code
a[i]= *(p+i);
is assigning a[i] to a random address. You should just try to rewrite this program. There a lot of errors in this program that I didn't even correct. Go on Google an look up finding even numbers in array program or something similar and look at the code of those examples.
EDIT:
I found some code examples for you to use. I hope it helps!
StackOverflow
sanfoundry.com
The caller already knows the address of the array, so you just need to return the new length. If we also remove the unused variables and take advantage of C++ declarations, we will have:
int getEvenNumbers(int* arr, int N)
{
for (int i = 0, k = 0; i < N; i++) {
if (arr[i] & 1 == 0) { // even if lowest bit is zero
arr[k] = arr[i];
k++;
}
}
return k;
}
Now you can print the even numbers easily:
int k = getEvenNumbers(arr, N);
printf("\n\nEven numbers in the array are as follows:\n\n");
for (i = 0; i < k; i++) {
printf("\n[%d] = %d", (i+1), arr[i]);
}
Dynamically allocate memory from heap.
int* a= new int [N];
//Now store the elements from index 1.
// at a[0] store the number of even number you have found in this function.
return a;
In main you know how many even numbers are there.
int *a1=getEvenNumbers(arr,n);
count_even=a1[0];
for(index=1;index<=count_even;index++)
cout<<a1[index];
The code is given here-
#include<stdio.h>
#include<stdlib.h>
int* getEvenNumbers(int arr[], int N)
{
int i, k = 1 , p;
int* a=new int[N+1];
for (i = 0; i < N; i++)
{
if (arr[i] % 2 == 0)
a[k++]=arr[i];
}
a[0]=k-1;
return a;
}
int main ()
{
int i, N;
printf("\nEnter your desired length of the array:\n\n");
scanf("%d", &N);
int arr[N];
for (i = 0; i < N; i++)
arr[i]= rand();
int *a=getEvenNumbers (arr, N);
printf("\n\nEven numbers in the array are as follows:\n\n");
for (i = 1; i <= a[0]; i++)
printf("\n[%d] = %d", (i), a[i]);
delete []a;
}
A better option is to use std::vector.You can read it here.
Related
Good evening, folks.
I'm currently experiencing difficulties with extracting pair numbers from an array. I have the following code:
#include <iostream>
using namespace std;
int *paire(int *d, int length) {
int counter = 0;
int position = 0;
for (int i=0; i<length; i++) {
if (d[i] % 2 ==0)
counter++;
}
int *k = new int[counter];
for (int i=0; i<length; i++) {
if (d[i] % 2 ==0) {
k[position] = d[i];
position++;
}
}
return k;
}
int main() {
int b[8] = {1,2,3,4,5,6,7,8};
int *array1 = paire(b,8);
for (int i=0; i<5; i++) { // how can I point here to the counter in paire() ?
cout<<array1[i];
}
delete[] array1;
return 0;
}
So I think I've got it right with initializing the new array in function paire, but I'm having difficulties to iterate through the array.
P.S. I'm first year in university, so I would really be thankful if you can keep the same simplicity in the answers. Thanks in advance!
It appears that you need to return 2 separate values: the number of even numbers in the array b, and the address of the newly allocated memory that is storing exclusively those even numbers.
Since you can not return multiple variables, one solution that does minimal modification to your code would be as follows.
int *paire(int *d, int length, int& counter) {
counter = 0;
// rest of your function remains unchanged
// ...
}
int main() {
int b[8] = {1,2,3,4,5,6,7,8};
int evenNumbers;
int *array1 = paire(b,8, evenNumbers);
for (int i=0; i<evenNumbers; i++) {
cout<<array1[i];
}
delete [] array1;
return 0;
}
Alternatively, you can return the value in counter and send the reference to the int* variable as an argument to paire function. Or, you can declare paire to have return type void and use references to pass back both the values.
You can further simplify your function by allocating to that of the length and returning the counter by an output parameter.
#include <iostream>
using namespace std;
int *paire(int *d, int length, int &counter) {
counter = 0;
int *k = new int[length]; // allocate for the maximum memory
for (int i = 0; i < length; ++i) {
if (d[i] % 2 == 0) {
k[counter++] = d[i];
}
}
return k;
}
int main() {
int b[8] = {1,2,3,4,5,6,7,8};
int counter = 0;
int *array1 = paire(b,8, counter);
for (int i=0; i<counter; i++) { // how can I point here to the counter in paire() ?
cout<<array1[i] << " ";
}
delete [] array1;
return 0;
}
But please note that as others have already pointed out this method is quite error prone in the sense that it leaves the responsibility to the client to delete the internal memory used by paire function.
I am having a problem in getting the contents of the variable 'arr' which is an array of pointers.
I tried,p *arr#n, but it gives the following output: $1 = {0x603010, 0x603030}.
What should I do?
int n, q;
scanf("%d %d", &n, &q);
int lastAnswer=0, index_size[n], *arr[n]; // <-- here
for(int i=0; i<n; i++)
index_size[i] = 0;
for(int i=0; i<n; i++) {
int *temp = malloc(sizeof(int)*n);
arr[i] = temp;
}
while(q--) {
int w, x, y, seq;
scanf("%d %d %d", &w, &x, &y);
if(w == 1) {
seq = ((x ^ lastAnswer) % n);
arr[seq][index_size[seq]++] = y;
}
else {
seq = ((x ^ lastAnswer) % n);
lastAnswer = y%n;
printf("%d\n", lastAnswer);
}
}
return 0;
If you print out a pointer itself, it would just give you an address in your memory block.
So print *arr#n would simply give you the content of the first dimension (an array of address in your output)
If you want to print out the deeper content. You might want to do something like this:
print **arr#n;
or
print *arr[0]#n
Another method would be define a pretty print function inside your program and call it in gdb.
void print(int arr[][], n, m)
{
int i, j;
for (i = 0; i < n; ++i)
{
for (j = 0; j < m; ++j)
printf("%d ", arr[i][j]);
printf("\n");
}
}
And call it in gdb by
call print(arr, n, m)
I don't think gdb support printing 2D array itself, why?
Because the definition of print *array#3 isn't printing the first three elements in array, instead, it is "priting *array (or array[0]) and the three elements following array[0].
print **arr#n#n
would not work in this case, (although it print out an nice format)
I cant find out whats wrong with this part of my program, i want to find out most occuring number in my structure(array), but it finds only the last number :/
void Daugiausiai(int n)
{
int max = 0;
int sk;
for(int i = 0; i < n; i++){
int kiek = 0;
for(int j=0; j < n; j++){
if(A[i].datamet == A[j].datamet){
kiek++;
if(kiek > max){
max = kiek;
sk = A[i].datamet;
}
}
}
}
}
ps. its only a part of my code
You haven't shown us enough of your code, but it is likely that you are not looking at the real result of your function. The result, sk is local to the function and you don't return it. If you have global variable that is also named sk, it will not be touched by Daugiausiai.
In the same way, you pass the number of elements in your struct array, but work on a global struct. It is good practice to "encapsulate" functions so that they receive the data they work on as arguments and return a result. Your function should therefore pass both array length and array and return the result.
(Such an encapsulation doesn't work in all cases, but here, it has the benefit that you can use the same function for many different arrays of the same structure tape.)
It is also enough to test whether the current number of elements is more than the maximum so far after your counting loop.
Putting all this together:
struct Data {
int datamet;
};
int Daugiausiai(const struct Data A[], int n)
{
int max = 0;
int sk;
for (int i = 0; i < n; i++){
int kiek = 0;
// Count occurrences
for(int j = 0; j < n; j++){
if(A[i].datamet == A[j].datamet) kiek++;
}
// Check for maximum
if (kiek > max) {
max = kiek;
sk = A[i].datamet;
}
}
return sk;
}
And you call it like this:
struct Data A[6] = {{1}, {2}, {1}, {4}, {1}, {2}};
int n = Daugiausiai(A, 6);
printf("%d\n", n); // 1
It would be nice if you had english variable names, so I could read them a bit better ^^. What should your paramter n do? Is that the array-length? And what should yout funtion do? It has no return value or something.
int getMostOccuring(int array[], int length)
{
int current_number;
int current_count = 0;
int most_occuring_number;
int most_occuring_count = 0;
for (int i = 0; i < length; i++)
{
current_number = array[i];
current_count = 0;
for (int j = i; j < length; j++)
{
int test_number = array[j];
if (test_number == current_number)
{
current_count ++;
if (current_count > most_occuring_count)
{
most_occuring_number = current_number;
most_occuring_count = current_count;
}
}
}
}
return most_occuring_number;
}
this should work and return the most occuring number in the given array (it has a bad runtime, but is very simple and good to understand).
So I am trying so merge 2 sorted arrays into one and I get really weird numbers like an output. Here is my code:
#include<iostream>
using namespace std;
int* add(int first[],int second[], int sizeFirst, int sizeSecond)
{
int result[sizeFirst + sizeSecond];
int indexFirst = 0,indexSecond = 0;
for(int i = 0;i < sizeFirst + sizeSecond;i++)
{
if(indexFirst == sizeFirst || first[indexFirst] > second[indexSecond])
{
result[i] = second[indexSecond];
indexSecond++;
}
else
{
result[i] = first[indexFirst];
indexFirst++;
}
}
return result;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i = 0;i < n;i ++)
cin>>arr[i];
int m;
cin>>m;
int arr2[m];
for(int i = 0;i < m;i ++)
cin>>arr2[i];
int *res;
res = add(arr,arr2,n,m);
for(int i = 0;i < n + m;i ++)
cout<<res[i]<<" ";
return 0;
}
Notes: It sorts it properly, so the mistake is not there. Also I need to do it as a function because I will need it later on for some other stuff.
return result;
You are returning a pointer to local array, which gets destroyed immediately after - this is undefined behavior. You should either allocate it using new or use std::vector (which is preferred).
Also, int result[sizeFirst + sizeSecond]; is not valid C++ because the standard doesn't allow variable sized arrays (but int* result = new int[sizeFirst + sizeSecond]; is valid).
void sort(int* A,int l)
{
int j;
int B[l];
for(int i=0;i<l;i++)
{
j = largest(A,l);
B[l-i-1] = A[j];
A[j] = -1;
}
A = B;
}
int main()
{
.
int C[3] = {x,y,z};
...
sort(C,3);
cout<<C[0]<<C[1];
}
output is coming to be -1-1
But if we assign A[0] = B[0] and so on, then we are getting the right answer.
PS: I've tried using *A = *B, which is only giving the first element to be correct.
When you assign A = B, you re-assign a local variable that holds a pointer to the first element of your array. This assignment will not change anything in main. In particular, the contents of A will not be affected.
You must copy all the elements from B to A after you have finished your sorting:
void sort(int *A, int l)
{
int j;
int B[l];
// sort into temporary array B
for (int i = 0; i < l; i++) {
j = largest(A, l);
B[l - i - 1] = A[j];
A[j] = -1;
}
// copy temporary array B to result array A
for (int i = 0; i < l; i++) A[i] = B[i];
}
But if you look at it, Amol Bavannavar was basically right: You don't have to check the whole array for the largest element each time. It is enough to check the remaining elements. So instead of assigning a low value to "used" elements, you could swap the largest elements to the end. When you do that, you'll see that the processed elements are at the end, the unprocessed elements are at the beginning. Then you can do your sorting in place without the need of a temporary array:
void sort2(int *A, int l)
{
while (l) {
int j = largest(A, l--);
int swap = A[j]; A[j] = A[l]; A[l] = swap;
}
}
There are many wrong uses of code in your example, for instance:
int B[l];
cannot be done, if you do it like this l must have a constant value.
A = B;
will perform a shallow copy instead of a deep copy.
You can see the diffrence here: What is the difference between a deep copy and a shallow copy?
cout<<C[0]<<C[1];
will print the numbers joined together without parsing.
As to how to fix this code one implementation you might be aiming towards can be:
#include <iostream>
using namespace std;
int largest(int* A, int l)
{
int big=-1;
int i;
int index=0;
for(i=0;i<l;i++)
{
if(A[i]>big)
{
big=A[i];
index=i;
}
}
return index;
}
void sort(int* A,int l)
{
int j;
int *B=new int[l];
for(int i=0;i<l;i++)
{
j = largest(A,l);
B[l-i-1] = A[j];
A[j] = -1;
}
for(int i=0;i<l;i++)
{
A[i]=B[i];
}
}
int main()
{
int C[3] = {2,5,1};
sort(C,3);
cout<<C[0]<<" "<<C[1];
return 1;
}