From my current understanding:
Every thread has its own stack
For a local variable int a in main(), it's on the stack of main()
After a thread created in main(), they can both access the same a. Wait a minute...?
What's wrong of my reasoning...
I should probably not to guess but here is it: It seems like on the perspective of the thread the parent-stack is ... global?
(I know this is probably asked before but I cannot find the exact one explaining this)
variables that are inside a function are called local variables.
void function_1(){ int a,b;}
A and B can only be used inside this function. After the function is called, the variables will be destroyed.
Next example:
#include<stdio.h>
int main()
{
int a = 100;
{
/* variable a declared in this block is
completely different from variable
declared outside. */
int a = 10;
printf("Inner a = %d\n", a);
}
printf("Outer a = %d\n", a);
// signal to operating system everything works fine
return 0;
}
a can be used inside main()
Global Variable:
#include<stdio.h>
void func_1();
int a, b = 10; // declaring and initializing global variables
int main()
{
printf("Global a = %d\n", a);
printf("Global b = %d\n\n", b);
func_1();
// signal to operating system program ran fine
return 0;
}
void func_1()
{
printf("From func_1() Global a = %d\n", a);
printf("From func_1() Global b = %d\n\n", b);
}
A and B can be used inside main() and func_1().
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)
I'm attempting to modify an array using only pointers.
void modify(){
int *ptr = &b[2];
*ptr = 90;
}
//I have my main function
void main() {
int b[15];
//fill the array with values using loop..skipping this part
modify();
}
The error that its giving me is : error: use of undeclared identifier 'b'
Can anyone give me some insight as to why the compiler does not recognize the array b?
b is declared as a local variable in main(), and thus can only be accessed by main(). To make b visible to other functions, make it a global variable by declaring it outside of any functions:
int b[3];
void modify(){
int *ptr = &b[2];
*ptr = 90;
}
int main(void) { //This is one of the standard signatures of main
//Fill the array with values using a loop
modify();
return 0; //main returns an int
}
I would like learn how to pass, by reference, an array of structs to the second function called/executed from within the first function. My goal is to modify/change the contents of arbitrary struct from the second function only. The code below works, but, unfortunately, does not do exactly what I want to achieve. I would to have access to arbitrary struct within second function. In other words, I would like to process all structs (using for loop) within second function by calling/executing first function in main only once and not using for loop.
The second function, in the code below, is named passByReference_inner.
array_of_struct.h :
struct card
{
int face;
int nose;
};
typedef struct card HEAD ;
/* prototype */
extern void passByReference(HEAD **c); /* first function */
extern void passByReference_inner(HEAD *c); /* second function */
first function: (passByReference)
#include <stdio.h>
#include "array_of_struct.h"
void passByReference(HEAD **c)
{
passByReference_inner (*c); /* second function */
}
second function: (passByReference_inner)
#include <stdio.h>
#include "array_of_struct.h"
void passByReference_inner(HEAD *c)
{
c->face = (c->face) + 1000;
c->nose = (c->nose) + 2000;
}
main:
#include <stdio.h>
#include "array_of_struct.h"
int main(void)
{
int i;
static HEAD c[12];
static HEAD *cptr[12];
for ( i = 0; i < 12; i++ )
{
c[i].face = i + 30;
c[i].nose = i + 60;
cptr[i] = &c[i];
}
for ( i = 0; i < 12; i++ )
{
passByReference(&cptr[i]); /* first function */
}
return 0;
}
I think what you are trying to do is this
#include <stdio.h>
struct card
{
int face;
int nose;
};
typedef struct card HEAD ;
/* prototype */
void passByReference(HEAD *c, int count); /* first function */
void passByReference_inner(HEAD *c); /* second function */
void passByReference(HEAD *c, int count)
{
int i;
for (i = 0 ; i < count ; i++)
passByReference_inner (&(c[i])); /* second function */
}
void passByReference_inner(HEAD *c)
{
c->face = (c->face) + 1000;
c->nose = (c->nose) + 2000;
}
int main(void)
{
int i;
HEAD c[12]; /* you don't need static here (do you know what static is for?) */
for ( i = 0; i < 12; i++ )
{
c[i].face = i + 30;
c[i].nose = i + 60;
}
/*
* the element count of the array is sizeof(c) / sizeof(c[0])
* (totalSizeOfArray) / (indivudualElementSizeOfArray).
*/
passByReference(c, sizeof(c) / sizeof(c[0])); /* first function */
return 0;
}
what you should know is that arrays in c decay to a pointer that points to their first element when passed as parameters to functions.
Since you want to process all the structs in the second function, I don't see the need for the first function, anyway this is how you would do it then
#include <stdio.h>
struct card
{
int face;
int nose;
};
typedef struct card HEAD ;
/* prototype */
void passByReference(HEAD *const c, int count); /* first function */
void passByReference_inner(HEAD *const c, int count); /* second function */
void passByReference(HEAD *const c, int count)
{
passByReference_inner(c, count); /* second function */
}
/* HEAD *const c prevents the pointer c to be changed
* this way it will never point anywhere else.
*
* And you can be sure to alter the original data.
*/
void passByReference_inner(HEAD *const c, int count)
{
for (int i = 0 ; i < count ; ++i)
{
c[i].face = (c[i].face) + 1000;
c[i].nose = (c[i].nose) + 2000;
}
}
int main(void)
{
int i;
HEAD c[12]; /* you don't need static here (do you know what static is for?) */
for ( i = 0; i < 12; i++ )
{
c[i].face = i + 30;
c[i].nose = i + 60;
}
/*
* the element count of the array is sizeof(c) / sizeof(c[0])
* (totalSizeOfArray) / (indivudualElementSizeOfArray).
*/
passByReference(c, sizeof(c) / sizeof(c[0])); /* first function */
return 0;
}
since you are effectively passing a pointer, you alter it's contents directly in both functions the first and the second.
One more thing, you don't really need the static keyword, specially in main(), static keeps the value of the variable between function calls, and since main() will normally be called only once in the lifetime of the program... it doesn't make much sense to use static there.
Your second function is correct.
A pointer to the first element of an array is effectively the same thing as the pointer to an array itself.
What you should do is
void passByReference_inner(HEAD *c, size_t n)
{
}
So, you'll pass the pointer to the first element of the array, and the number of elements in the array, something like this:
passByReference(c, sizeof(c)/sizeof(c[0]));
This will pass the pointer to the first element of the c array, and the number of elements in the array, to passByReference_inner(). sizeof(c) is the size of the entire array in bytes. sizeof(c[0]) is the size of an element in the array. So, if, for example, each struct is 10 bytes long (just an example), and you have an array of 12 structs, the size of the entire array is 120 bytes, and this calculates the value 120/10=12, the number of elements in the array, automatically.
When you use the name of an array object, in C/C++ that automatically becomes a pointer to the first element of the array.
In your function, you can work with the array in the following manner:
void passByReference_inner(HEAD *c, size_t n)
{
for (size_t i=0; i<n; i++)
{
HEAD *p=c+i;
// p is now a pointer to the ith element of the array
}
}
Adding an integer n to a pointer advances the pointer to the next nth element of an array. Adding an integer value to a pointer doesn't advance the pointer by this number of bytes, but by the number of bytes in the object the pointer points to, multiplied by the number you're adding (or subtracting, same thing). That makes pointer arithmetic do the right thing.
The following code compiles cleanly.
The following code moves the increment values loop
to inside the passByReference() function.
/*
* Note: guard code is used in a header file
* so the header file can only be included once
* in each compilation unit
*/
// note the inclusion of a 'guard' wrapper
// begin: array_of_struct.h file
#ifndef ARRAY_OF_STRUCT_H
#define ARRAY_OF_STRUCT_H
struct card
{
int face;
int nose;
};
// dont obsecure the code with useless typedef statements
//typedef struct card HEAD ;
#define MAX_CARDS (12)
/* prototype */
extern void passByReference(struct card *pCards); /* first function */
extern void passByReference_inner(struct card *pCard); /* second function */
#endif
// end: array_of_struct.h
//first function: (passByReference), in different file
#include <stdio.h>
#include "array_of_struct.h"
void passByReference(struct card *pCards)
{
int i=0; // loop index
for(i=0;i<MAX_CARDS;i++)
{
passByReference_inner (&pCards[i]); /* second function */
} // end for
} // end function: passByReference
// second function: (passByReference_inner), in different file
#include <stdio.h>
#include "array_of_struct.h"
void passByReference_inner(struct card *pCard)
{
pCard->face = (pCard->face) + 1000;
pCard->nose = (pCard->nose) + 2000;
} // end function: passByReference_inner
//main, in a different file
#include <stdio.h>
#include "array_of_struct.h"
int main()
{
int i = 0; // loop index
static struct card cards[MAX_CARDS];
for ( i = 0; i < MAX_CARDS; i++ )
{
cards[i].face = i + 30;
cards[i].nose = i + 60;
} // end for
passByReference(&cards[0]); /* first function gets ptr to whole array*/
// could also be written as:
// passByReference(cards);
return 0;
} // end function: main
I've analyzed all three solutions (iharob, user3629249, Sam Varshavchik) and came to the conclusion that Sam Varshavchik and the second solution from iharob were right on the money. The first iharob's solution and user3629249 solution are, in essence, equal. They moved for loop from main to the first function. The second solution of the iharob's post matches the requirements from the initial post. Sam's solution gave me enough hints/instructions for 'how to move for loop from the main to the second function (which was, basically, what I did not know how to do it and therefore asked for help).
So, to make long story short, here is the source code which implements almost all suggestions from all contributors. The code compiles cleanly, so, beginners like me, can take it as-is and learn few details about pointer to pointer, pointer arithmetic and about array of structs.
array_of_struct.h (header file)
#ifndef ARRAY_OF_STRUCT_H
#define ARRAY_OF_STRUCT_H
/* HEAD structure definition */
typedef struct
{
int face;
int nose;
} HEAD; // end structure HEAD
#define MAX_HEADS (12)
/* prototype */
extern void passByReference(HEAD **c, size_t n);
extern void passByReference_inner(HEAD *c, size_t n);
#endif
passByReference.c (first function)
#include <stdio.h>
#include "array_of_struct.h"
void passByReference(HEAD **c, size_t n)
{
passByReference_inner (*c, n);
}
passByReference_inner.c (second function)
#include <stdio.h>
#include "array_of_struct.h"
void passByReference_inner(HEAD *c, size_t n)
{
int i;
HEAD *p;
printf("\nPOINTER ARITHMETIC: The value of struct's members after PASS BY REFERENCE \n");
for ( i = 0; i < n; i++ )
{
p = c + i;
p->face = (p->face) + 1000;
p->nose = (p->nose) + 2000;
printf("struct[%i].face = %d \n",i, p[0].face);
printf("struct[%i].nose = %d \n",i, p[0].nose);
}
printf("\nARRAY INDEX MATH: The value of struct's members after PASS BY REFERENCE\n");
printf("[NOTE: structs were updated in the for loop above]\n");
for ( i = 0; i < n; i++ )
{
printf("struct[%i].face = %d \n",i, c[i].face);
printf("struct[%i].nose = %d \n",i, c[i].nose);
}
}
main.c
#include <stdio.h>
#include "array_of_struct.h"
int main(void)
{
int i;
HEAD c[MAX_HEADS];
HEAD *cptr;
size_t n;
n = (sizeof(c) / sizeof(c[0]);
printf("\nINITIALIZATION of all struct's members\n");
for ( i = 0; i < n; i++ )
{
c[i].face = i + 30;
c[i].nose = i + 60;
printf("struct[%i].face = %d\n",i, c[i].face);
printf("struct[%i].nose = %d\n",i, c[i].nose);
}
cptr = &c[0];
passByReference(&cptr, n);
return 0;
}
I've got a struct called members which contains a bunch of char arrays and integers. The struct has been declared in Header.h and defined it by "struct members pt" in source.c, inside main. From here a for-loop is being runned 5 times and adding variables to the character arrays and ints in pt[x].
Now I need to be able to access this from a function called void search(int a); (Should probably not be a void since I want it to return a value. But I'll fix that later)
What void search is supposed to do is basicly
int willReturn[10];
int b = 0;
for(int x = 0; x<a; x++)
{
if(pt[x].hasPayed == 0)
{
willReturn[b] = x;
b++;
}
}
There might be something wrong about that code, but the thing that I need to know is how I can access pt[x].hasPayed.
Any ideas?
I do not want to use any global variables.
Thank you in advance.
Below sample code might help you.
header.h
struct members {
int hasPayed;
};
main.c
#include <stdio.h>
#include <string.h>
#include "main.h"
typedef struct members MEMBERS;
void print_member(MEMBERS *pt) {
int i;
for(i =0 ; i< 10; i++)
{
printf(" %d\n",pt[i].hasPayed);
}
}
void main () {
MEMBERS pt[10];
int i;
for(i =0 ; i< 10; i++)
{
pt[i].hasPayed= i;
}
print_member(pt);
}
Instead of print_member code your search logic.
Pass a pointer to pt as a paraamter to search. e.g void search(int a, struct members *pt).
Another way if you don't want to pass pointers. Place pt in a function as a static variable.
struct members** ____get_pt(){
static struct members pt[ /* size */ ];
/*
or for dynamical size,
static struct members* pt;
*/
return &pt;
}
// Define a macro for convenience, above where you want to use 'pt'.
#define PT (*____get_pt())
Then you can use PT[x].hasPayed everywhere, without global variables.
However, this could do not improve your code ...