int funcc(int a[],int b[],int *cnt)
{
int *c;
int j,i,s=0;
for (i=0;i<n;i++)
for (j=0;j<n;j++)
if(b[i]==a[j])
{
*cnt++;
break;
}
c=(int*)malloc(*cnt*sizeof(int));
for (i=0;i<n;i++)
for (j=0;j<n;j++)
if(b[i]==a[j])
{
c[s++]=b[i];
break;
}
return c;
}
void main (void)
{
int *c;
int *cnt=0;
int i,arr[n]={3,2,1},brr[n]={3,2,0};
c=funcc(arr,brr,&cnt);
for(i=0;i<*cnt;i++)
printf("%d ",c[i]);
}
I need to print the common numbers in 2 arrays..
but the problem is with "cnt" .. if i replace cnt with 3 it works ..
but when i put cnt it doesnt work
The problem is you declare cnt as an int pointer, so when you pass in &cnt, you're passing in a pointer to a pointer to an int. Try changing that second line of main to int cnt=0; and change the for loop to for(i=0;i<cnt;i++) (notice the removal of the * character).
EDIT: the line *cnt++; should be changed to either ++*cnt; or (*cnt)++, since the increment operator takes higher precedence than the dereference operator.
Your prototype is:
int funcc(int a[],int b[],int *cnt)
but you are passing it a pointer to a pointer:
int *cnt=0; /* <- pointer */
int i,arr[n]={3,2,1},brr[n]={3,2,0};
c=funcc(arr,brr,&cnt); /* &cnt <- pointer to a pointer */
Related
I am writing a program that creates an array of random numbers from 1 to 100 and sorts them in ascending order. Below is working code that does this, but I need to modify it so that the "swap" function makes use of pointers. The call for the swap function should look like this: swap(???,???) where the two inputs are pointers. What is the best way to accomplish this?
#include<stdio.h>
#include<math.h>
int main()
{
void fillArray(int sizeArray, int array[sizeArray]);
void printArray(int sizeArray, int array[sizeArray]);
void sortArray(int sizeArray, int array[sizeArray]);
int sizeArray;
printf("\nSize of the array? ");
scanf("%d", &sizeArray);
int array[sizeArray];
fillArray(sizeArray,array);
sortArray(sizeArray, array);
printArray(sizeArray, array);
}
void fillArray(int sizeArray, int array[sizeArray])
{
int increment;
for(increment=0; increment<sizeArray; increment++)
{
array[increment]=rand()%101;
}
}
void sortArray(int sizeArray, int array[sizeArray])
{
void swap(int increment2, int increment, int array[]);
int increment, increment2, temp;
for (increment=0; increment < sizeArray ; increment++)
{
for (increment2=increment+1; increment2 < sizeArray; increment2++)
{
swap(increment2, increment, array);
}
}
}
void swap(int increment2, int increment, int array[])
{
int temp;
if (array[increment2] < array[increment])
{
temp=array[increment];
array[increment]=array[increment2];
array[increment2]=temp;
}
}
void printArray(int sizeArray, int array[sizeArray])
{
int increment=0;
printf("\nHere's the sorted array:\n");
while(increment<21)
{
printf("\n array[%d] is %d", increment, array[increment]);
increment++;
}
}
The output should look like this:
output
Define your swap function as below:
void swap(int *increment2, int* increment)
Modify your for loop where you call the swap function:
for (increment=0; increment < sizeArray ; increment++)
{
for (increment2=increment+1; increment2 < sizeArray; increment2++)
{
swap(array[increment2], array[increment]);
}
}
Then, modify your swap function:
void swap(int *increment2, int* increment)
{
int temp;
if (increment2 < increment)
{
temp= *increment2;
*increment2=*increment;
*increment2=temp;
}
}
You need to fix your function call for the parameters to be with pointers.
void swap(int *increment2, int* increment)
Then in your swap function you need
You will need to deference the integer*.
Example
int n1;
int* x = 100
n1 = *x;
You may need to
deference in the future example
Your function accepts pointers
void swap(int *increment2, int* increment)
If you have integers or another data type to reference them, refer to their address, you can perform & for referencing.
int i = 5;
int* x;
x = &i;
x is now an integer pointer to the address of i.
Your calling code needs to pass the address of the integers to compare and swap. Either of the following forms is acceptable, and they are equivalent.
swap(array+increment2, array+increment);
swap(&array[increment2], &array[increment]);
The first form takes the address of the first element (array) and adds the index (increment2) to get the address of the correct element.
The second version is more straightforward, perhaps. It uses the & address-of operator to take the address of array[increment2], which is the desired integer.
Your swap function need to be defined as follows:
void swap(int** p2, int** p1)
{
int temp;
if (*p2 < *p1)
{
temp=*p1;
*p1=*p2;
*p2=temp;
}
}
Note how the pointers are dereferenced with the * operator to get the integer values for comparison (and storage in temp).
I'm trying to scan numbers into 2 2D arrays, and I keep on getting the error of redefinition.
The code:
#include <stdio.h>
#define N 3
void getMatrix(double mat[N][N]);
/*
char getMenuOption();
void getCoordinates(int*, int*);
void sumMatrices(double mat1[][N], double mat2[][N]);
void changeMatrix(double mat[][N]);
void printMatrix(double mat[][N]);
*/
int main() {
double A[N][N], B[N][N];
/*
char option;*/
getMatrix( A[N][N]);
getMatrix( B[N][N]);
/*
option = getMenuOption();*/
return 0;
}
void getMatrix(double A[N][N]){
int i;
for(i=0;i<=N;i++){
for(i=0;i<N;i++)
{
scanf("%lf",&A[N][N]);
}
}
return;
}
void getMatrix(double B[N][N]){
int i;
for(i=0;i<=N;i++){
for(i=0;i<N;i++)
{
scanf("%lf",&B[N][N]);
}
}
return;
}
I guess the problem is that the same function is called twice, but im not so sure about it.
If anyone can help me point to the problem, it will be most welcome.
You don't need to define a function twice (to call it twice or more). One function can be called multiple times, that's the reason of having functions in first place. Get rid of
void getMatrix(double B[N][N]){
int i;
for(i=0;i<=N;i++){
for(i=0;i<N;i++)
{
scanf("%lf",&B[N][N]);
}
}
return;
}
Having said that, you should call the function like
getMatrix(A);
getMatrix(B);
To pass the array (the decay to pointer, anyway). The notation A[N][N] denotes a member of the array and for an array defined like
double A[N][N];
it's off-by-one, as array indexing in C starts from 0.
The function is defined twice
First definition
void getMatrix(double A[N][N]){
int i;
for(i=0;i<=N;i++){
for(i=0;i<N;i++)
{
scanf("%lf",&A[N][N]);
}
}
return;
}
Second definition
void getMatrix(double B[N][N]){
int i;
for(i=0;i<=N;i++){
for(i=0;i<N;i++)
{
scanf("%lf",&B[N][N]);
}
}
return;
}
Take into account that these calls of the function are invalid
getMatrix( A[N][N]);
getMatrix( B[N][N]);
The arguments have type double instead of arrays or pointers.
You should remove one definition of the function and declare the function correctly.
If the compiler allows to use Variable Length Arrays then the functiuon should be declared like
void getMatrix(size_t n, double A[n][n]);
if Variable Length Arrays are not supported by the compiler then N must be a constant and the function indeed can be declared like
#define N SOME_VALUE
//...
void getMatrix( double A[N][N] );
and call the function like
in the first case
getMatrix( N, A );
getMatrix( N, B );
and in the second case
getMatrix( A );
getMatrix( B );
I have 2 arrays. I read them trough a function. Then I sum them trough another function and print the sum array trough another function. I have to use pointers all the time. Problem is, it prints the sum of the last two elements of the array as the whole sum array. How can I fix this?
#include<stdio.h>
void read(int *pdato);
void print(int *pdato);
void sum(int *pdato1,int *pdato2, int *pdato);
int main(){
int A[5],B[5],C[5],i;
printf("Data for first array:\n");
read(A);
printf("Data for the second array\n");
read(B);
sum(A,B,C);
printf("Result:\n");
print(C);
return 0;
}
void read(int *pdato){
int i;
for(i=0;i<5;i++){
printf("[%d]:",i);
scanf("%d",pdato);
}
}
void sum(int *A,int *B, int *C){
int i;
for(i=0;i<5;i++){
*(C+i)=*(A+i)+*(B+i);
}
}
void print(int *pdato){
int i;
for(i=0;i<5;i++){
printf("[%d]:%d\n",i,*pdato);
}
}
Should be
printf("[%d]:%d\n",i,pdato[i]);
and
scanf("%d",&pdato[i]);
Building off of #Massey101, here is the answer without using array notation:
Should be
printf("[%d]:%d\n",i,*(pdato + i));
and
scanf("%d",pdato + i);
Another solution is below. Increment pointer after every data read to point to correct memory location to store inputs.
for(i=0;i<5;i++) {
scanf("%d",pdato);
pdato++;
}
Increment pointer while printing results, so that it will fetch results from correct memory location as show below
for(i=0;i<5;i++) {
printf("[%d]:%d\n",i,*pdato);
pdato++;
}
#include<stdio.h>
#include<conio.h>
float smallest(int arr[],int k,int n);
void sort(int arr[],int n);
void main()
{
int arr[20],i,n,j,k;
clrscr();
printf("\nEnter the number of elements in the array: ");
scanf("%d",&n);
printf("\nEnter the elements of the array");
for(i=0 ; i < n ; i++)
{
printf("\n arr[%d] = ",i);
scanf("%d",&arr[i]);
}
sort(arr,n);
printf("\nThe sorted array is: \n");
for(i=0 ; i < n ; i++)
printf("%d\t",arr[i]);
getch();
}
int smallest(int arr[],int k,int n)//smallest function
{
int pos=k,small=arr[k],i;
for(i=k+1;i<n;i++)
{
if(arr[i]<small)
{
small=arr[i];
pos=i;
}
}
return pos;
}
void sort(int arr[],int n)//sorting function
{
int k,pos,temp;
for(k=0 ; k < n ; k++)
{
pos=smallest(arr,k,n);
temp=arr[k];
arr[k]=arr[pos];
arr[pos]=temp;
}
}
In the above program the sort function is being called from main but the return type of sort is void and it still returns the sorted array. As after sorting the array the function should return the sorted array back to the calling function to print the sorted array but the program runs perfectly. How is that happening?
When you declare
int arr[20];
you can say "arr is an array of 20 integers". But arr is a pointer to an integer as well, pointing to the first integer in a row of 20. So de-referencing *arr is an integer, the same as arr[0] in fact.
This means when you pass arr to a function you only pass a pointer to that function. The function in this case works on the (copied) pointer. But this very pointer points exactly to the same memory as your original arr declared in main(). And that's the reason why manipulating arr in sort() is in fact manipulating arr in main().
When passing an array as a parameter, this
int smallest(int arr[],int k,int n)
means exactly the same as
int smallest(int *arr,int k,int n)
For example
#include<iostream>
void printArray(int data[])
{
for(int i = 0, length = sizeof(data); i < length; ++i)
{
std::cout << data[i] << ' ';
}
std::cout << std::endl;
}
int main()
{
int data[] = { 5, 7, 8, 9, 1, 2 };
printArray(data);
return 0;
}
You will see that only the first 4 elements of the array are printed. The sizeof(data) returns a value of 4! That happens to be the size of the pointer used to pass the array to printArray().
First the array does not get copied. The pointer to the first element of the array is copied
First, there is no connection between any function argument what is, or is not passed using a return statement with an expression according to the function's return type.
While it is true that all parameter passing in C is by value - copy the value to a "local parameter variable" - nothing is assumed about what is to happen at the memory location a pointer is referencing. So, a function can make any changes in the calling environment, even without returning a value.
As to parameters declared as being aType name[]. this is merely syntactic sugar for const aType* name.
I am trying to create a program in C that removes duplicate values in an integer array. My strategy is to first sort the array via a selectionsort function, and then call a function removedup that removes any consecutive, duplicate values in the array.
My code:
#include <stdio.h>
#include "simpio.h"
#define n 10
void GetArray(int a[]);
void SelectionSort(int a[]);
int FindMax(int a[], int high);
void swap(int a[], int p1, int p2);
int removedup(int a[]);
void printArray(int a[]);
main()
{
int a[n];
GetArray(a);
SelectionSort(a);
printf("The original, sorted array is\n");
printArray(a);
printf("The array with removed duplicates \n");
printArray(removedup(a));
getchar();
}
void GetArray(int a[])
{
int i;
for(i=0;i<n;i++)
{
printf("Enter integer# %d", i+1);
a[i]=GetInteger();
}
}
void SelectionSort(int a[])
{
int i, max;
for(i=0;i<n;i++)
{
max=FindMax(a,n-i-1);
swap(a,max,n-i-1);
}
}
int FindMax(int a[], int high)
{
int i, index;
index=high;
for(i=0;i<high;i++)
{
if(a[i]>a[index])
index=i;
}
return index;
}
void swap(int a[], int p1, int p2)
{
int temp;
temp=a[p2];
a[p2]=a[p1];
a[p1]=temp;
}
int removedup(int a[])
{
int i, count, OutArray[count], j;
count=0;
for(i=0;i<n-1;i++)
{
if(a[i]==a[i+1])
{
a[i+1]=a[i+2];
count++;
}
}
count++;
for(j=0;j<count;j++)
{
OutArray[i]=a[i];
}
return OutArray;
}
I have two questions:
1) How do I fix the error the compiler in giving me in the main body when calling removedup inside the printarray function, saying "invalid conversion from int to int*"? (line 22)
2) How do I accurately define the size of OutArray[] in the removedup function? Currently I have it defined as the size variable, but the value of this variable isn't accurately defined until after the declaration of OutArray.
Notice your prototypes ...
int removedup(int a[]);
void printArray(int a[]);
And also notice you're calling printArray() with the result of removedup().
printArray(removedup(a));
The result of removedup() is an int; printarray() requires a int[].
int and int[] are not compatible.
I suggest you remove duplicates and print array in two distinct statements.
You should be able to fix the compiling problems after reading comp.lang-c FAQ on arrays and pointers.
After you get your array sorted, you can use the following function to remove the duplicates:
int dedup(int arr[], int size) {
int curr = 0, next = 0;
while (next < size) {
while (next < size && arr[next] == arr[curr])
next++;
if (next < size)
arr[++curr] = arr[next++];
}
return size ? curr+1 : 0;
}
It takes two arguments, the array and its size. The duplicates are removed in-place, which means that the array is modified, without allocating a new array to store the unique elements.
Remember that the dedup function expects the elements to be sorted! I've noticed you are using your own implementation of selection sort, which makes me think this is homework. In that case, I feel a little reluctant on giving you a complete solution, although understanding it should be a good exercise anyway.
EDIT: I should've explained the last line of code.
return size ? curr+1 : 0; is equivalent to:
if (size)
return curr+1;
else
return 0;
Just a shorter way of saying the same thing.