Program in c with functions without pointers doesn't work [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
I have written a code and it doesn't run. However, there are no mistakes in compiler. I am stuck, could you give me a hint please where am I wrong?
I am 95% sure it is about checktable function.
P.S. I know how to do it with pointers, but I try to understand how to make it without them.
Thank you!
#include <stdio.h>
#include "genlib.h"
void fillarray (int a[50])
{
int i;
for(i=0;i<50;i++)
a[i]=rand()%10;
}
void printarray (int a[50])
{
int i;
for(i=0;i<50;i++)
printf(" %d ", a[i]);
}
int number()
{
int num;
printf("Give the number!");
num=GetInteger();
return num;
}
void checktable (int a[50], int b[50], int ar,int count)
{
int i;
count=0;
for(i=0;i<50;i++)
if (a[i]==ar)
{
b[count]=i;
count++;
}
}
main()
{
int i,a[50], b[50], N,count;
fillarray(a);
printarray(a);
N=number();
checktable(a,b,N,count);
printf("the number is used %d times", count);
printf("in places:");
for(i=0;i<count;i++)
printf("%d ",b[i]);
getch();
}

Approach 1: The "pointer" way:
In your code, change
void checktable (int a[50], int b[50], int ar,int count)
to
void checktable (int a[50], int b[50], int ar,int *count)
and call it as checktable(a,b,N,&count);
Approach 2: The "return" way:
Otherwise, the count which is updated in checktable() won't be reflected in main().
However, Alternatively (without using pointers), IMO, its always easier to simply return the number of occurrences via return statement. In that case , code will look like
int checktable (int a[50], int b[50], int ar)
{
int i;
int count=0;
for(i=0;i<50;i++)
if (a[i]==ar)
{
b[count]=i;
count++;
}
return count;
}
and the calling will be
count = checktable(a,b,N);
Note: Its always a good practice to initialize your variables.

If you don't want to use pointers,then you can return count and assign it to the count variable in main. I've improved your code here with all of it explained in the comments inside the code:
#include <stdio.h>
#include <stdlib.h> //Don't forget this header for srand and rand
#include <time.h> //For the time in srand
#include <conio.h> //For using getch()
#include "genlib.h"
void fillarray (int a[]) //leave the brackets empty
{
int i;
for(i=0;i<50;i++)
a[i]=rand()%10;
}
void printarray (int a[]) //here too
{
int i;
for(i=0;i<50;i++)
printf(" %d ", a[i]);
}
int number()
{
int num;
printf("\n\nGive the number!");
num=GetInteger();
return num;
}
int checktable (int a[], int b[], int ar) //Use int to return an int
//No need for count parameter
{
int i,count;
count=0;
for(i=0;i<50;i++)
if (a[i]==ar)
{
b[count]=i;
count++;
}
return count; //returning count
}
int main() //Use int main
{
int i,a[50], b[50], N,count;
srand(time(NULL)); //For rand to generate random numbers
fillarray(a);
printarray(a);
N=number();
count=checktable(a,b,N); //set count to the return value of checktable
//Also,no need to pass count as a parameter
printf("The number is used %d times", count);
printf(" in places:");
for(i=0;i<count;i++)
printf("%d ",b[i]+1); //Don't forget +1 otherwise output might come as place 0
getch();
return 0; //main returns int
}

Related

Error: Expression expected before 'i' in C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed last year.
Improve this question
I have written a C code to accept values via an array of structures which asks the user in the main function to choose whether he/she wants to input char or int values and sort the array via insertion sort and print it, but I am getting an
error from the compiler: {error]: expected expression before i
#include<stdio.h>
int n;
typedef struct ls{
int a;
char l;
}i[50],ls;
int main(){
printf("Enter the value\n");
scanf("%d",&n);
ls int1;
int ans;
printf("Main Menu\n");
printf("1.)integer sort \n2.)Characrter sort\n");
scanf("%d",&ans);
if(ans==1){
intSort(i.a);
}
else if(ans==2){
charSort(i.l);
}
else{
exit(0);
}
int ans1;
printf("Would you like to print the array\n");
scanf("%d",&ans1);
if(ans==1 && ans1==1){
display(i.a);
}
else{
display(i.l);
}
}
int intSort(int a[]){
int j;
printf("Enter the values into the array \n");
for(j=0;j<n;j++){
scanf("%d",&a[j]);
}
// insertion sort function call
insertionSort(a);
return 1;
}
int charSort(char a[]){
int j;
printf("Enter the values into the array \n");
for(j=0;j<n;j++){
scanf(" %c",&a[j]);
}
insertionSort(a);
return a;
}
int insertionSort(int a[]){
int temp,i,j;
for(i=1;i<n;i++){
temp= a[i];
j=i-1;
}
while(j>=0 && temp<a[j]){
a[j+1]=a[j];
j-=1;
}
a[j+1]=temp;
return 1;
}
int display(int a[]){
int i;
printf("Sorted array:");
for(i=0;i<n;i++){
printf("%d ",a[i]);
}
}
You are defining the type incorrectly. If I understand correctly, you want do have a typedef ls and then initialize an array of your newly defined structures. You would want to do something like this:
#include <stdlib.h>
#include <stdio.h>
typedef struct ls {
int a;
char l;
} ls;
int main() {
int i;
ls *array_of_ls = malloc(50*sizeof(*array_of_ls));
for (i = 0; i < 50; i++) {
array_of_ls[i].a = i;
array_of_ls[i].l = 65+i;
printf("ls[%d] = (%d, %c)\n", i, array_of_ls[i].a, array_of_ls[i].l);
}
free(array_of_ls);
}
Of course, make sure you handle exceptions, etc. But this should get you going.

Pointing to arrays using void function

Sorry for that title. I really didn't know how to define this problem.
I was needed to declare integer array of N numbers and to fill it with random nums in void function. Then that array needs to be printed in main. The thing is that i am not allowed to use printf in void function so only way to print in main is to use pointers I guess. My knowledge is limited as I am beginner at pointers. Thx in advance and sorry for bad english.
Here is my code so far. When I compile it marks segmentation error.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void form();
int main()
{
int N, a[100];
printf("Input index: \n");
scanf("%d", &N);
form(N, &a);
printf("Array: \n");
for (int i = 0; i < N; i++) {
printf("a[%d] = %d", i, a[i]);
}
}
void form(int N, int *ptr[100])
{
srand(time(NULL));
for (int i = 0; i < N; i++) {
*ptr[i] = rand() % 46;
}
There are several issues in your code.
1) Your array decalaration form() is obsolete. Use proper prototype.
2) For declaring a VLA, declare it after reading N instead of using a fixed size array.
3) An array gets converted into a pointer to its first element when passed to a function. See: What is array decaying?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void form(int, int*); /* see (1) */
int main(void) /* Standard complaint prototype for main.
If you need to pass arguments you can use argc, and argv */
{
int N;
printf("Input size: \n");
scanf("%d", &N);
int a[N]; /* see (2) */
form(N, a); /* see (3) */
printf("Array: \n");
for (int i = 0; i < N; i++) {
printf("a[%d] = %d", i, a[i]);
}
}
void form(int N, int *ptr) { /* Modified to match the prototype
srand(time(NULL));
for (int i = 0; i < N; i++) {
ptr[i] = rand() % 46;
}
}
So a couple things:
void form();
As Olaf was alluding to, this declaration is incorrect - you are missing the applicable parameters. Instead, it should be
void form(int N, int ptr[100]);
The main reason your program is crashing is because of the following line:
*ptr[i] = rand() % 46;
You are dereferencing the pointer at i, which is actaully giving you a number - what you want is to assign the value of the pointer at i the new random value:
ptr[i] = rand() % 46;
As related reading, see this question about passing an array in as a function parameter (basically, int ptr[] is the same thing as int * ptr)
Small modifications on your code:
1) Correction and simplification of parameter handling at function call. Just hand over "a", it's an array, so it is an address, you can use int *ptr, or int ptr[], or int ptr[100] in the formal parameter list for it. So you can use simply ptr[i] in your function.
2) Make a prototype for function from old-style declaration providing parameter list.
3) int i; declaration before the for loop - not mandatory, depends on your compiler standard
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void form(int N, int *ptr);
int main()
{
int N, a[100];
printf("Input index: \n");
scanf("%d", &N);
form(N, a);
printf("Array: \n");
int i;
for (i = 0; i < N; i++) {
printf("a[%d] = %d", i, a[i]);
}
}
void form(int N, int *ptr)
{
srand(time(NULL));
int i;
for (i = 0; i < N; i++) {
ptr[i] = rand() % 46;
}
}

Function printArray not working properly

I'm trying to make function that prints array but the output of it is wrong.
Can someone help me please?
This is the code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void printArr(int arr[],int size);
int main()
{
int arr1[3] = { 1,2,3 };
int arr2[5] = { 1,2,3,4,5 };
printf("arr1: \n");
printArr(arr1, 3);
printf("\n\narr2: \n");
printArr(arr2, 5);
printf("\n\n");
return(0);
}
void printArr(int arr[], int size)
{
int i;
for (i = 0; i < size; i++);
{
printf("%d", arr[i]);
}
}
What I get is:
Remove the semi-colon at the of for:
for (i = 0; i < size; i++);
^^^
That makes the for loop run size times and executes the block after that. But by that time, i value is equal to size. This leads to out of bound access, which is undefined behaviour. Clearly, this is not what you intention was.

What changes do I have to make to my code so it also sorts negative numbers?

#include<stdio.h>
void countingSort(int array[], int k, int n){
int i,j;
int B[100],C[1000];
for (i=0;i<=k;i++)
{
C[i]=0;
}
for (j=0;j<n;j++)
{
C[array[j]]++;
}
for (i=1;i<=k;i++)
{
C[i]+=C[i-1];
}
for (j=0;j<n;j++)
{
B[--C[array[j]]]=array[j];
}
printf("Sortiran niz je: \n");
for(i=0;i<n;i++)
{
printf("%d ", B[i]);
}
printf("\n");
}
void max(int array[], int *k,int n){
int i;
printf("Broj elemenata u nizu je %d\n",n);
for(i=0;i<n;i++)
{
if(array[i]>*k) {
*k=array[i];
}
}
}
int main(int brArg, char *arg[]){
FILE *ulaz;
ulaz=fopen(arg[1],"r");
int array[1000];
int i=0,j,k=0,n,x,m;
while(fscanf(ulaz,"%d", &array[i])!=EOF)
i++;
fclose(ulaz);
n=i;
max(array,&k,n);
countingSort(array,k,n);
return 0;
}
My code works excellent for positive integers but I need to modify it so it can also sort negative integers. I hope you can help me. I don't have anything else to say but I can't post a question unless I write something here about it, so I hope it's enough.
Use a linked list, the generic list Glist exists in the GObject library. If you only need to deal with 32bit integers you can use it with very little extra programming. As you read the integers from file perfom an insertion sort in that while loop.

Passing array to function using pointer

I'm trying to print array of pointer using pointer instead of array but I got this error Segmentation fault at runtime:
enter number of element:5
array[0]=1
array[1]=2
array[2]=3
array[3]=4
array[4]=5
Segmentation fault
This is the code:
#include <stdio.h>
#include <stdlib.h>
int *array;
int n;
void input(int *array,int n);
void display(int *array,int n);
int sum(int *array,int n);
int main (void) {
int result;
printf("enter number of element:");scanf("%d",&n);
input(array,n);
display(array,n);
result=sum(array,n);
printf("sum of array=%d",result);
return 0;
}
void input(int *array,int n){
int j;
array=(int *)malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);scanf("%d",array+j);
}
}
void display(int *array,int n){
int j;
for(j=0;j<n;j++)
printf("%d\t",*(array+j));
printf("\n");
}
int sum(int *array,int n){
int sum=0,j;
for(j=0;j<n;j++)
sum+=*array+j;
return sum;
}
How can I fixed this code? please somebody explain me what's wrong with that code.
Variable array is a local variable in function input.
As such, it is pointless to set it with array = ..., because this assignment takes effect only inside the function. You should typically pass its address (&array) to any function that needs to change it.
In your specific example, you also have a global variable array, so a quick solution to your problem would be to simply call function input without passing variable array as an argument:
void input(int n)
{
...
array = (int*)malloc(n*sizeof(int));
...
}
int main()
{
...
input(n);
...
}
Note that this is a "dirty" workaround, and you should typically strive to avoid the use of global variables.
To add the clean version to barak's answer:
int input(int ** array, const size_t n)
{
int result = 0;
assert(NULL != array);
(*array) = malloc(n * sizeof(**array));
if (NULL == (*array))
{
result = -1;
}
else
{
size_t j;
for(j = 0; j < n; ++j)
{
printf("array[%zu]=", j);
scanf("%d", (*array) + j); /* still missing error checking here . */
}
}
return result;
}
And call it like this:
if (-1 == input(&array, n))
{
perror("input() failed");
exit(EXIT_FAILURE);
}
Try this input():
void input(int **array,int n){
int j;
*array=(int *)malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);scanf("%d",*array+j);
}
}
Because C use pass-by-value, if you want to change the value of a variable in a function, you need to pass the address of that variable as the argument to that function.
In this case, you want to change the value of array in input() and the type of array is int *, therefore the prototype of input() should be something like void input (int **array, ...).
this should do..make sure you understand what the others have said..
#include <stdio.h>
#include <stdlib.h>
int *array;
int n;
void input(int **array,int n);
void display(int **array,int n);
int sum(int **array,int n);
int main (void) {
int result;
printf("enter number of element:");scanf("%d",&n);
input(&array,n);
display(&array,n);
result = sum(&array,n);
printf("sum of array= %d",result);
return 0;
}
void input(int **array,int n){
int j;
*array= malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);
scanf("%d",(*array)+j);
}
}
void display(int **array,int n){
int j;
for(j=0;j<n;j++){
printf("%d\t",*((*array)+j)); // you can use array notation aswell
//array[0][j] will work
}
printf("\n");
}
int sum(int **array,int n){
int sum=0,j;
for(j=0;j<n;j++){
sum += *((*array)+j);
}
return sum;
}
What does *array + j do? Does it evaluate *array and add j to it? Or does it add j to array and then dereference it? Would you be willing to bet $100 on it if I told you you are wrong?
Make your life and the life of anybody reading your code easier by using parentheses, or even better, write array [j].

Resources