Getting value from a pointer parameter of a function in C - c

as I am starting to study at university we are learning how to write in C and we got to the point where I've learned that I can use pointers as function parameters but what they haven't told us is how to get the value from it. I am not able as a person who doesn't know about C as much, to come up with other solution than use two parameters (one as pointer to the variable and other as value. See the example which is not real code but it's just for purpose of demonstration:
int main(int argc, char* argv []) {
int a;
addNumber(&a);
}
void addNumber(int * a) {
*a = *a + 1; // this obviously does not work
}
Any input would be appreciated.
Thanks!

Only one major thing: You forgot to initialize a. Otherwise, it looks fine.
int a = 0;
addNumber(&a);
The only other thing is that you're missing the return statement in main.

Here is an example that may be closer to what you are looking for:
#include <stdio.h>
void increment(int *a, int *b)
{
*a = *a + *b;
}
int main(void)
{
int sum = 5;
int increment_by = 7;
printf("sum: %d, increment_by: %d\n", sum, increment_by);
increment(&sum, &increment_by);
printf("sum: %d, increment_by: %d\n", sum, increment_by);
return 0;
}
output:
$ ./bar
sum: 5, increment_by: 7
sum: 12, increment_by: 7

It will work. It will work better if you initialise a, to some value.

Related

C language - Invoking functions based on index value passed as argument - array of pointers to functions

Thank you for taking the time to read this, I looked for answers before posting but I'm very new to the language. This exercise I'm trying to do is from the book "Effective C: An introduction to professional C programming".
This is my first go at learning the language, and the exercise from the 2nd chapter of the book is as follows:
Declare an array of three pointers to functions and invoke the appropriate function based on an index value passed in as an argument
I am not totally sure I understand what it's saying, but I have a piece of functioning code I think does the job. However, I'm not sure if I'm interpreting it correctly. Here's my code:
#include <stdio.h>
#include <stdlib.h>
void f0(int x) {
printf("I am f0 and in index location %d\n", x);
}
void f1(int x) {
printf("I am f1 and in index location %d\n", x);
}
void f2(int x) {
printf("I am f2 and in index location %d\n", x);
}
int main(void){
void (*f0p)(int);
f0p = &f0;
void (*f1p)(int);
f1p = &f1;
void (*f2p)(int);
f2p = &f2;
void *array[3] = {f0p, f1p, f2p};
for (int i = 0; i < 3; i++) {
void (*program)(int);
program = array[i];
program(i);
}
return 0;
}
this works after compiling and returns the following:
I am f0 and in index location 0
I am f1 and in index location 1
I am f2 and in index location 2
However, am I completing the exercise correctly? I don't think I'm technically using the index as an argument and calling the function, but I'm a noob. Any validation or correction / education you provide would be extremely appreciated. I spent many hours on this today!
Pointers should not be converted between pointers-to-functions and pointers-to-objects (including void) except in special situations.
The array is better declared as an array of pointers to functions:
void (*arrray[])(int) = { f0, f1, f2 };
and the functions can be called without an intermediate variable:
array[i](i);
You can also typedef functions and use syntax similar to "normal" pointers and arrays.
typedef void functype(int);
void f0(int x) {
printf("I am f0 and in index location %d\n", x);
}
void f1(int x) {
printf("I am f1 and in index location %d\n", x);
}
void f2(int x) {
printf("I am f2 and in index location %d\n", x);
}
int main(void)
{
functype *array[] = {f0, f1, f2};
functype *ptr = f0;
for(int x = 0; x < sizeof(array) / sizeof(array[0]); x++)
{
array[x](x);
}
ptr(4);
}

C - swapping two 2D arrays by switching pointers

I would like to swap two variables containing 2D arrays. I believe this can be simply done by swapping their pointers. I tried this code, but it does not work and I have no idea why, perhaps I am not understanding pointers correctly.
#include <stdio.h>
void swap(int ***a, int ***b) {
int ** temp = *a;
*a = *b;
*b = temp;
}
int main(void) {
int a[10][10];
int b[10][10];
a[1][5] = 4;
b[1][5] = 2;
printf("%d, %d\n", a[1][5], b[1][5]);
swap(&b, &a);
printf("%d, %d\n", a[1][5], b[1][5]);
return 0;
}
This outputs
4, 2
4, 2
I would expect it to output
4, 2
2, 4
So, what am I doing wrong?
a and b in main function are not pointers but arrays.
If you want to use pointers, use pointers.
#include <stdio.h>
#define N 10
void swap(int (**a)[N][N], int (**b)[N][N]) {
int (*temp)[N][N] = *a;
*a = *b;
*b = temp;
}
int main(void) {
int a[N][N];
int b[N][N];
int (*pa)[N][N] = &a;
int (*pb)[N][N] = &b;
(*pa)[1][5] = 4;
(*pb)[1][5] = 2;
printf("%d, %d\n", (*pa)[1][5], (*pb)[1][5]);
swap(&pb, &pa);
printf("%d, %d\n", (*pa)[1][5], (*pb)[1][5]);
return 0;
}
This would not work because what you are swapping is actually what the variables in the swap() function are pointing to, and not what they are pointing at. Its like if a was pointing at 5 and b was pointing at 6 in the swap() function, then it will make a point at 6 and b point at 5, without changing the contents of the memory. This would mean the in the main() function they would be residing at the same place and would be getting pointed by the same variable a and b (different from the variable in swap())
To swap you need to swap the contents of that memory in the swap() function, so that it is reflected in the main() function.
Recall that while doing swapping using pointers, one sends the address and actually swaps the content by dereferencing (*p and *q).

Swapping variables with a function doesn't affect the call site

A few lessons ago I learned about variables, and got a question in my homework about swapping two numbers - I used a third variable to solve this question.
The solution looked somewhat like this:
#include <stdio.h>
int main(void) {
int x, y;
scanf("%d %d", &x, &y);
// swappring the values
int temp = x;
x = y;
y = temp;
printf("X is now %d and Y is now %d", x, y);
}
Now I'm learning about functions, and I wanted to try and solve the previous question with a helper swap function.
This is the code I've written:
#include <stdio.h>
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
int main(void) {
int a = 3, b = 4;
swap(a, b);
printf("%d %d\n", a, b);
}
I don't know why, but the output is still 3 4 even though I changed the value inside the swap() function.
Why is this happening?
Pass address of x and y as arguments to function. Right now they are local variables, changes are not made to original variables .
Do as follows-
void swap(int *x,int *y){
/* dereference pointers and swap */
int temp = *x;
*x = *y;
*y = temp;
}
And call in main like this -
swap(&x,&y);
What you are doing is passing parameter by value. It means that during the function call, copies of parameters are created. So inside the function you are working on copies of actual variables.
Instead you need to pass it as a reference. Please read more about pass-by-value vs pass-by-reference.
#include <stdio.h>
void swap(int& x,int& y) //Instead of passing by value just pass by reference
{
int temp=x;
x=y;
t=yemp;
}
int main() {
int a=3,b=4;
swap(a,b);
printf("%d %d\n",a,b);
return 0;
}
EDIT:
C does not have references. Above code will work in c++ instead. To make in work in C, just use pointers and de-reference it inside the function.

Initialization makes pointer from integer without a cast - C

Sorry if this post comes off as ignorant, but I'm still very new to C, so I don't have a great understanding of it. Right now I'm trying to figure out pointers.
I made this bit of code to test if I can change the value of b in the change function, and have that carry over back into the main function(without returning) by passing in the pointer.
However, I get an error that says.
Initialization makes pointer from integer without a cast
int *b = 6
From what I understand,
#include <stdio.h>
int change(int * b){
* b = 4;
return 0;
}
int main(){
int * b = 6;
change(b);
printf("%d", b);
return 0;
}
Ill I'm really worried about is fixing this error, but if my understanding of pointers is completely wrong, I wouldn't be opposed to criticism.
To make it work rewrite the code as follows -
#include <stdio.h>
int change(int * b){
* b = 4;
return 0;
}
int main(){
int b = 6; //variable type of b is 'int' not 'int *'
change(&b);//Instead of b the address of b is passed
printf("%d", b);
return 0;
}
The code above will work.
In C, when you wish to change the value of a variable in a function, you "pass the Variable into the function by Reference". You can read more about this here - Pass by Reference
Now the error means that you are trying to store an integer into a variable that is a pointer, without typecasting. You can make this error go away by changing that line as follows (But the program won't work because the logic will still be wrong )
int * b = (int *)6; //This is typecasting int into type (int *)
Maybe you wanted to do this:
#include <stdio.h>
int change( int *b )
{
*b = 4;
return 0;
}
int main( void )
{
int *b;
int myint = 6;
b = &myint;
change( &b );
printf( "%d", b );
return 0;
}
#include <stdio.h>
int change(int * b){
* b = 4;
return 0;
}
int main(){
int b = 6; // <- just int not a pointer to int
change(&b); // address of the int
printf("%d", b);
return 0;
}
Maybe too late, but as a complement to the rest of the answers, just my 2 cents:
void change(int *b, int c)
{
*b = c;
}
int main()
{
int a = 25;
change(&a, 20); --> with an added parameter
printf("%d", a);
return 0;
}
In pointer declarations, you should only assign the address of other variables e.g "&a"..

*Pointer = - *Pointer?

I've only been doing C for a few weeks so I am quite new to it.
I've seen things like
* (variable-name) = -* (variable-name)
in lecture notes but what exactly would it do? Would it just negate the value being pointed to?
Yes. When you add the star it means it is pointing to the value.
It is essentially saying: to the value at address (variable-name), become -1* the value of (variable-name).
If you are new to C, you may find it easier to use & instead of pointers. &'s are essentially the opposite of *. & doesn't point, it gives the address of a variable (which I find to be a simpler concept).
The following is an example which should demonstrate the use of * and &.
#include <stdio.h>
int main(void)
{
int blah = 6;
int *num = &blah;
(*num) = -(*num);
printf("%d\n", num); //Displays num
}
Yes it negates the value being pointed to. We cannot write operations on addresses so operations are done on deferenced pointers. Here, *d = -*c means:
*d = (-1) * (*c)
Sample code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *c;
int *d;
d = (int *)malloc(sizeof(int));
c = (int *)malloc(sizeof(int));
*c = 9;
*d = -*c;
printf("%d", *d);
free(c);
free(d);
return 0;
}

Resources