C Auto variables - c

Variables declared as auto variables are local to the blocks in which they are defined in C.
Consider the code below,
#include<stdio.h>
#include<string.h>
char *fun();
int main()
{
char *s;
s= fun();
printf("%s\n", s);
return 0;
}
char *fun()
{
char buffer[30];
strcpy(buffer, "RAM");
return (buffer);
}
This is a code I found on net (it was a MCQ question). The output is unpredictable and so throws error since buffer is an auto array and will die when the control go back to main. Thus s will be pointing to an array , which not exists.
Now consider this code.
#include<stdio.h>
int sum(int x,int y)
{
int c=x+y;
return c;
}
int main()
{
int a=1,b=2;
int c=sum(a,b);
printf("%d",c);
}
In this code, the variable c is also an auto variable declared inside the function sum which means it is local to that function and cannot be accessed outside the function. But how does this code compile successfully without throwing any error. Why?

The difference is that in the first example you're returning a pointer with the address to a variable. This pointer is not valid after the variable goes out of scope. In your second example, you're just copying the value of the variable.
This works:
int sum(int x,int y) {
int c=x+y;
return c;
}
But not this
int *sum(int x,int y) {
int c=x+y;
return &c;
}
However, this does, because it's not an auto variable:
int *sum(int x,int y) {
static int c=x+y;
return &c;
}

Related

transfer of pointer from function to function

I have a problem, because while loading data from the console, a bug is popping up I think it's a tricky thing to pass the indicator through the function, but I don't know how to fix it.
#include<stdio.h>
#include<stdlib.h>
typedef struct rn{
int n; /**numerator**/
unsigned d; /**denomirator**/
} rationalNumber;
typedef struct dot{
rationalNumber x;
rationalNumber y;
} point;
int gcd(int a, int b)
{
if(b!=0)
return gcd(b,a%b);
return a;
}
void input(rationalNumber *a)
{
int nwd;
if (scanf("%d/%u",&(a->n), &(a->d)) == 1) a->d=1;
else
{
nwd = abs(gcd(a->n, a->d));
a->n = a->n/nwd;
a->d = a->d/nwd;
}
}
void load_point(point *a, void(*function)(rationalNumber *))
{
function(&a->x);
function(&a->y);
}
int main(void)
{
rationalNumber *z;
point *a;
load_point(a, input);
return 0;
}
I've got this message : Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
in this place : if (scanf("%d/%u",&(a->n), &(a->d)) == 1) a->d=1;
You're creating pointers that point to nothing in particular and then pass these on to the function which never initializes them, allocates memory for them, and trusts that they're valid, but they're not.
Remember that point* a is a pointer, not an allocation.
An easy solution is to use local variables instead of pointers:
int main(void)
{
rationalNumber z;
point a;
load_point(&a, input);
return 0;
}

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.

C subscripted value is neither array nor pointer nor vector

Can you guys help me on function m? The idea is to printf the "tab", but i don't understand what is wrong
#include <stdio.h>
#define MAXL 50
#define MAXC 50
unsigned int linhas;
unsigned int colunas;
int segC [MAXL];
int segL [MAXC];
char tab[MAXL][MAXC];
void c (){
int l,c,temp;
scanf("%d %d",&linhas,&colunas);
for (l=0;l<linhas;l++){
scanf("%d[^'']",&temp);
segC[l]=temp;
}
for (c=0;c<colunas;c++){
scanf("%d[^'']",&temp);
segC[c]=temp;
}
for(l=0;l<=linhas;l++){
for(c=0;c<colunas;c++){
scanf("%c",&tab[l][c]);
}
}
}
char m (linhas,colunas,segC,segL,tab){
int l,c;
int tempi;
char tempc;
for(l=0;l<=linhas;l++){
for(c=0;c<colunas;c++){
printf("%c",tab[l][c]);
}
tempi=segL[l];
printf("%d\n",tempi);
}
for(c=0;c<colunas;c++){
tempi=segC[c];
printf("%d",tempi);
}
printf("\n");
}
char h (int line){
}
int main (){
c();
//m(linhas,colunas,segC,segL,tab);
}
Rewrite the function like this:
char m() {
/* ... */
}
You do not need to provide global variables as arguments to a function; in fact, the local function parameters shadow the global variables.
Finally, avoid omitting parameter and variable types; that is at the very least deprecated or even illegal as of C99 (omitted types default to int which is causing the problem here.)
Better yet, declare them as local variables in main() and pass them by pseudo-reference to both m() and c():
char m( unsigned int linhas, unsigned int colunas, int **segC, int **segL, char ***tab ) {
/* ... */
}
Pass the address of segC, segL, and tab when calling.
You're missing variable types:
char m (linhas,colunas,segC,segL,tab)

Printing an int in C

I am trying to print an int a before and after calling a set function to set the value of a. I am doing this in C. When I compile it I have no errors but when I attempt to run it, I get a segmentation fault.
Here is what I have so far:
#include <stdio.h>
int main(){
int* a;
printf("%d",*a);
set(10);
printf("%d", *a);
return 0;
}
int set(int*a, int val){
*a = val;
return *a;
}
int main(){
int* a;
printf("%d",*a);
What you have there is a pointer to an int rather than an actual int.
And, while that's the correct way to print the int it points to, unfortunately it points to an arbitrary memory location which is why you're crashing.
You are not allowed to dereference arbitrary pointers, they have to point to something valid, such as if you begin your code with:
int main(){
int target_of_a = 42;
int *a = &target_of_a;
printf ("%d", *a);
In addition, you probably should be calling set with something like:
set (a, 10);
something the compiler would generally warn you about though, in this case, it would probably just say it didn't know about set at the time you called it. If it had known, it could have told you about the parameter mismatch.
One way for you to acheive that is to ensure you have a prototype defined for the function before you call it:
int set(int*,int);
or just move the function to before main. With all those changes (and a bit of a general tidy up), you'd end up with:
#include <stdio.h>
int set (int *a, int val) {
*a = val;
return *a;
}
int main (void) {
int target_of_a = 42;
int *a = &target_of_a;
printf ("%d\n", *a);
set (a, 10);
printf ("%d\n", *a);
return 0;
}
The wisdom of returning the variable you're changing is also debatable but there are situations where that might be useful (such as if you want to us it immediately without another statement: printf ("%d\n", set (a, 10)); for example) so I've left that as is.
I should also mention that it's a little unusual to artificially create a pointer variable in a situation like this.
Now it may be that your code is just a simplification of some more complex scenario where you already have a pointer but, if not, the usual way to do this would be to just have the int itself and just use & to create one on the fly:
#include <stdio.h>
int set (int *a, int val) {
*a = val;
return *a;
}
int main (void) {
int a = 42;
printf ("%d\n", a);
set (&a, 10);
printf ("%d\n", a);
return 0;
}
This code should work:
#include <stdio.h>
#define FIRST_VALUE 20
#define SECOND_VALUE 10
int main(){
int a = FIRST_VALUE; /* Declare a as an int variable. */
printf("Before set: a = %d\n",a); /* Print the first value. */
set(&a, SECOND_VALUE); /* Pass the ADDRESS of a to set. */
printf("After set: a = %d\n", a); /* Print the new value of a. */
return 0;
}
int set(int*a, int val){
*a = val;
return *a;
}
Note that the variable a in main() is not the same as the variable a in set(); you have to pass a pointer to a to set() in order for set() to operate on it.
Try this:
And remember, all functions before the main() (if you're using only one file)
Take a read on value and reference params.
#include <stdio.h>
int set(int* a, int val){
*a = val;
}
int main(){
int a = 2;
printf("%d\n", a);
set(&a, 10);
printf("%d\n", a);
return 0;
}

Getting a sub-function to modify variables

This is a simple test program where I am trying to get the func function to modify the variables a and b which are then used in the main function. Is there a way to get func to return the modified variables so they can be used? (preferably without using struct as I don't understand how it works)
#include <stdio.h>
void func(int a, int b)
{
a=a+1;
b=b+1;
}
void main(void)
{
int a=0, b=0;
while (1)
{
func(a,b);
printf("%d\n",a);
}
}
If you want to modify variables in the calling function, you have to pass their address to func (i.e. pass a pointer to these variables
void func(int* a, int* b)
{
*a=*a+1;
*b=*b+1;
}
func(&a,&b);
Your code passes its arguments by value. This means that a and b are copied into new variables which are initialised with the values of the calling variables but only exist for the duration of func.
I agree. The best way to do this is using pointers. But are you aware that your code will never terminate? You should use a condition that can end excution of the while loop.
Also, if you wanna perfom the exact same action to both variables you could just use the return statement like this:
#include <stdio.h>
void func(int a, int b)
{
return a+1;
}
void main(void)
{
int a=0, b=0;
while (a < 5)
{
func(a);
func(b);
printf("%d\n",a);
}
}
We can achieve through pointers . Don't use While(1) because it will go to infinite loop. I think following program help to you.
#include <stdio.h>
void func(int* a, int* b)
{
*a=*a+1;
*b=*b+1;
}
void main(void)
{
int a=0, b=0;
//while (1)
// {
func(&a,&b);
printf("%d\n",a);
// }
}

Resources