Use of Pointers in a separate function file - c

Working of Pointers
// swap.h
swap(int, int);
// swap.c
swap(int *i, int *j)
{
int k;
k=*i;
*i=*j;
*j=k;
}
// Practice.c
#include <stdio.h>
#include "swap.h"
main()
{
int i,j;
printf("\nEnter I = ");
scanf("%d",&i);
printf("\nEnter J = ");
scanf("%d",&j);
swap(&i, &j);
printf("\n I = %d",i);
printf("\n J = %d",j);
}
When I wrote this program in one file, the program was correctly executed. Now after I divided it into 2 parts, Practice.c that has main() function and swap.c that contains the swap(int *i, int *j) function, it did not go so well.
Here is the following process I used to execute the program.
gcc -c swap.c
gcc Practice.c swap.o -oPractice
As soon as I tried to execute the 2nd statement it did not compile and produced errors.
I used exactly the same process for executing another program, which had 3 files,
Practice.c { main() function }
Add.c { add() function }
Add.h { header file }
It did not have pointers.
Please tell me where I'm making the mistake.

In swap.h change
swap(int, int);
to
swap(int *, int *);
Your swap function takes integer pointers as parameters, but your declaration says to take integers. So compiler will give you errors.

Related

How to create a function from other 3 with the same signature in C

I'm working with C, and I'm trying to build a kind of "composite" function, by joining 2 functions with the same signature, and a third with almost the same signature but just one less argument. The functions should be executed in sequence, but the final function must have the same signature. You can think it as building a function with code blocks using same signature(I have it implemented in C++ with policy class, but I'm trying a C approach as the rest of the code is in C already).
I built some code very simple, just to explain my approach.
#include <stdio.h>
#include <stdlib.h>
typedef void simulFileProc(int a, int b);
typedef void simulRead(int a);
typedef struct compFunct{
simulFileProc* file1;
simulRead* read;
simulFileProc* file2;
} compFunct;
void realProc(int a, int b){
printf("call from realProc %d, %d\n",a,b);
}
void realRead(int a){
printf("call from read %d\n",a);
}
simulFileProc* join(int a, int b, compFunct* func){
void sf(int a, int b){
func->file1(a,b);
printf("intermediate line\n");
func->read(a);
func->file2(a,b);
}
return &sf;
}
int main() {
compFunct* c = malloc(sizeof(256));
c->file1 = &realProc;
c->read = &realRead;
c->file2 = &realProc;
int a=0;
int b=0;
simulFileProc* s = join(a,b,c);
s(4,3);
return 0;
}
It is working, but for some reason, just the first function print.
call from realProc 4, 3
intermediate line
If I comment the line "func->read(a);", I have a segmentation fault.
What is wrong ?? Is there a smarter way to do ?

How to create a dynamically sized global array?

I am making a multi-threaded program to find prime numbers in C. How do I take an input in the following C program and not use (#define N =88)?
I am getting the following error:
main.c:8:7: error: expected declaration specifiers or ‘...’ before string constant
scanf("%d", &N);
^~~~
#include <stdio.h>
#include <pthread.h>
#include <conio.h>
#define MAX_THREADS 4
int N;
scanf("%d", &N);
int prime_arr[N]={0};
void *printprime(void *ptr)
{
int j,flag;
int i=(int)(long long int)ptr;
while(i<N)
{
printf("Thread id[%d] checking [%d]\n",pthread_self(),i);
flag=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
{
flag=1;
break;
}
}
if(flag==0 && (i>1))
{
prime_arr[i]=1;
}
i+=MAX_THREADS;
}
}
int main()
{
pthread_t tid[MAX_THREADS]={{0}};
int count=0;
for(count=0;count<MAX_THREADS;count++)
{
printf("\r\n CREATING THREADS %d",count);
pthread_create(&tid[count],NULL,printprime,(void*)count);
}
printf("\n");
for(count=0;count<MAX_THREADS;count++)
{
pthread_join(tid[count],NULL);
}
int c=0;
for(count=0;count<N;count++)
if(prime_arr[count]==1)
printf("%d ",count);
return 0;
}
You can't have general statements outside of functions.
The simple solution is to read the input in the main function and then create the array in the main function as well.
And keep the array as a local variable inside the function, and pass it as an argument to the functions to call (together with its size).
To mass multiple arguments to the thread function, create a structure with the "arguments" as members, and pass a pointer to one such structure.

Function definition in Macros in C

This code throws out an error saying that "code undelcared."
#include<stdio.h>
#define MAIN() c##o##d##e
int main()
{
MAIN();
printf("C program");
return 0;
}
int code()
{
printf("C is life");
}
Whereas, this code runs smoothly.
#include<stdio.h>
#define MAIN() m##a##i##n
int main()
{
MAIN();
printf("C program");
return 0;
}
int code()
{
printf("C is life");
}
Output:
C program
This code also runs smoothly.
#include <stdio.h>
#define macro(n, a, i, m) m##a##i##n
#define MAIN macro(n, a, i, m)
int MAIN()
{
printf("C is life");
return 0;
}
Output:
C is life
In the first code, why doesn't the code work as like main? I don't know what is the process after the concatenation 'main' is completed by the macro. Kindly explain the process behind these codes, in simple terms. Thanks in advance.
I also tried by defining the code function.
#include<stdio.h>
#define MAIN() c##o##d##e
int code(void);
int main()
{
MAIN();
printf("C program");
return 0;
}
int code(void)
{
printf("C is life\n");
return 0;
}
Output:
C program
So, defining a function should not be the problem. My question is, what happens after concatenation? Thanks in advance.
In C (since the C99 standard) you need to declare all functions before you use them.
In the first example you haven't declared the code function before you attempt to use it. You solve it by adding a function prototype:
// Declare the function, also known as a function prototype
void code(void);
int main(void)
{
// ...
}
// Define the function
void code(void)
{
// ...
}
The second example works because you use main which is already declared at that point. If a function haven't been declared before, the definition also declares the function.
Also note that your macro after expansion doesn't actually call the code (or the main) function. This is good, since calling main recursively (directly or indirectly) is generally bad.
In C, you have to define the prototype of your function int code () before any calls :
int code (void);
The function main is declared in assembly code, this is why your second version compiles et runs correctly.
If you want to avoid this error please add -Wmissing-prototypes compilation flag in order to let the compiler checks for you if your function has a prototype.
The problem is that code() function is not yet declared when main() is compiled.
Either move code() before main():
#include<stdio.h>
#define MAIN() c##o##d##e
int code()
{
printf("C is life");
}
int main()
{
MAIN();
printf("C program");
return 0;
}
Or forward declare code():
#include<stdio.h>
#define MAIN() c##o##d##e
int code();
int main()
{
MAIN();
printf("C program");
return 0;
}
int code()
{
printf("C is life");
}
Just remember macros are replaced at preprocessor stage itself. In C, every function needs to be prototyped before using/calling it so that compiler knows in advance about it's arguments and return type to avoid conflicts.
Case 1 :- when below code blocks executes, macro name MAIN() got replaced with code.
#define MAIN() c##o##d##e
int main(){
MAIN();
printf("C program");
return 0;
}
int code(){
printf("C is life");
}
And it looks like below after pre-processor stage
int main(){
code; /* errorenous statement */
printf("C program");
return 0;
}
int code(){
printf("C is life");
}
observe the line code; in above code block, it cause the compilation error. When you run above code like gcc -Wall -Wstrict-prototypes -Werror test.c where it will convert warning into error.
error: ‘code’ undeclared (first use in this function) #define MAIN()
c##o##d##e
^
to solve this, declare the code() like before #define
int code(void); /* declaration */
There is one more warning converted into error
error: statement with no effect [-Werror=unused-value] #define MAIN()
c##o##d##e
Because after macro replacement it looks like code; and here compiler rightly complaining above statement with no effect. So to avoid this
change the macro name from MAIN() to MAIN. for e.g
#define MAIN c##o##d##e
Correct version of case-1 code
#include<stdio.h>
int code(void);
#define MAIN c##o##d##e
int main(void){
MAIN();
printf("C program");
return 0;
}
int code(void){
printf("C is life");
return 0;
}
And it produces output as
C is lifeC program
Case 2 :- when below code executes, macro name MAIN() gets replaced with main
#define MAIN() m##a##i##n
int main(){
MAIN();
printf("C program");
return 0;
}
int code(){
printf("C is life");
}
And it looks like at preprocessor stage
int main(){
main; /* it causes error */
printf("C program");
return 0;
}
int code(){
printf("C is life");
}
Case 3 :- when below code blocks executes, macro name MAIN() got replaced with code & here you declared the code() also.
#define MAIN() c##o##d##e
int code(void);
int main() {
MAIN();
printf("C program");
return 0;
}
int code(void) {
printf("C is life\n");
return 0;
}
And it looks like below after pre-processor stage
int code(void);
int main() {
code;/* error causing statement */
printf("C program");
return 0;
}
int code(void) {
printf("C is life\n");
return 0;
}
Suggest you to compile any C code with
gcc -Wall -Wstrict-prototypes -Werror test.c
so by converting warning to error you will learn more.

How to create multiple functions in C

I am new to C programming and I am trying to create functions. The first function executes but the second one doesn't.
#include <stdio.h>
char get_char();
int main(void)
{
char ch;
printf("Enter a character > ");
scanf("%c", &ch);
return ch;
}
int get_int()
{
int i;
printf("Enter an integer between 0 and 127 > ");
scanf("%d", &i);
return i;
}
For anyone else that arrives here, you may solve your problem, by making sure your main function is at the bottom of the file.
Why? Because if function a calls function b, a should be before b.
main is the entry point for your program. The C environment calls main when your program is executed. get_int() is not the name for an entry point, so the fact that you never call it directly or indirectly in main means it will never be executed.
You also didn't declare it before main meaning your compiler will warn about not finding it, but since get_int returns int it will link successfully regardless.
Fix:
int get_int();
int main ()
{
//...
}
int get_int()
{
//...
}
Your second function isn't called and it should be as follows:
int main()
{
int m = 10;
get_int(m);
return 0;
}
int get(int num)
{
int multiply = num * num;
return multiply;
}

c function and multiple value returning

My question is in general how to use pointers in functions correctly.
if to be more specific I need to write a function the recives 3 values from a user and then retruns it to the main one for further actions.
This is the code I have written so far:
#include <stdio.h>
#include <conio.h>
int inputThree(int, int, int);
int sortTwo(int, int);
int sortThree(int, int);
int main()
{
int a=0, b=0, c=0;
printf("before: func %d \n", b);
inputThree(a,b,c);
printf("after func: %d%d%d \n",a,b,c);
getch();
}
int inputThree(int a, int b, int c)
{
printf("Input three integers values: \n");
scanf("%d%d%d", &a, &b, &c);
return 0;
}
I'm intersted in understanding how to keep the values of scanf via pointers. When I return to the main function they are lost because they aren't global...
Also, I couldn't leave the function inputthree without parameters even though I want it to get them from scanf itself, so I had to put some values for it to run.
thanks in advance!
Pass pointers to the variables from main to inputThree.
Change the function declaration.
int inputThree(int* aPtr, int* bPtr, int* cPtr);
Change the call.
inputThree(&a, &b, &c);
Change the implementation.
int inputThree(int* aPtr, int* bPtr, int* cPtr)
{
printf("Input three integers values: \n");
scanf("%d%d%d", aPtr, bPtr, cPtr);
return 0;
}
You can either return a struct or make a function that handles passed pointers as argument.
#include <stdio.h>
struct Foo{
int x;
int y;
};
//one way
struct Foo do_work();
//or another
void do_work(int *x, int *y);
int main(void) {
return 0;
}
struct Foo do_work(){
//e.g.
struct Foo foo;
foo.x = 1;
foo.y = 2;
return foo;
}
void do_work1(int *x, int *y){
//e.g
*x = 1;
*y = 1;
}
Technically, only 1 thing (or none) can be returned from a function at a time. If you wanted to change the values of two or more variables via a function even after the function ends, you would need to pass into the function's parameters/arguments the memory reference of the variable.

Resources