my question is how does the function malloc_queue() can access variables from init_queue() without giving any arguments!
For example:
The main.c:
if (init_queue()) {
malloc_queue()
}
init_queue() creates the variable que:
int init_queue{
struct Queue *que;
return 1;
}
malloc_queue() want to do something with the variable que from init_queue():
void malloc_queue{
struct Queue *que = (struct Queue*)malloc(sizeof(struct Queue));
return;
}
but that doesnt work since malloc_queue doesnt know what que is. Are there any possible ways without giving any arguments?
Maybe you want a static variable outside functions, which has scope inside the residing file after its definition.
Check this code:
#include <stdio.h>
static int x = 0;
void a() {
x = 5;
}
void b() {
x*=2;
}
int main(int argc, char * argv[]) {
printf("%d\n", x);
a();
printf("%d\n", x);
b();
printf("%d\n", x);
return 0;
}
Just as the comments suggested, read about c scopes.
If you need to declare struct other than primary types, you might need to declare a pointer to structure as the static variable outside function, then allocate memory (e.g malloc()) inside one of your functions.
Related
Yesterday I had a problem with a function, turned out I forgot to declare a variable of the structure type, it is clear now what was the problem. I've modified my code, and I got another error messages, however it looks like the code actually s working.
I googled the problem but I can't really fit the solutions to my code. Can somebody shows and explain me what would be the clean way of the below code?
#include <stdio.h>
/*************************************************
include
**************************************************/
//A signal structure
typedef struct SIGNAL_STRUCTURE
{
int id;
int time;
}signal_structure;
//Structure what collects all the signals
typedef struct SIGNAL_COLLECTOR
{
signal_structure EngSpeed;
signal_structure TransReqGear;
signal_structure CurrentGear;
}signal_collector;
//Function to do with the above structure
void ManipulateSignal(signal_structure * signal)
{
signal->id = 10;
signal->time = 11;
}
/*************************************************
main
**************************************************/
void fcn(signal_collector * param_signal, int len)
{
int *pointer = param_signal;
while(len--)
{
ManipulateSignal(pointer);
pointer += (sizeof(signal_structure) / sizeof(int));
}
}
int main(void)
{
signal_collector foo;
fcn(&foo, 1);
return 0;
}
You can't use a typedef name as a function argument. You need to declare a variable with that type, and pass the address of the variable.
int main(void) {
param_collector my_pc;
fcn(&my_pc);
return 0;
}
You can only pass the reference to the object, but you forgot to define this object.
int main(void)
{
param_collector param_collector;
fcn(¶m_collector);
return 0;
}
but I would give rather call the variable a distinct name (not the same as type)
I have learned how to use functions and structs and pointers. I want to combined them all into one. But the code that I write doesn't seem to work. The compiler tells me the test is an undeclared identifier. Here is the code:
#include <stdio.h>
#include <stdlib.h>
struct character
{
int *power;
};
void test (use_power)
int main ()
{
test (use_power)
printf("%d\n",*power);
return 0;
}
void test ()
{
int use_power = 25;
struct character a;
a.power = &use_power;
}
Your code has many mistakes it can't even compile
Multiple missing semicolons.
Implicit declaration of test() here
test (use_power)
with a missing semicolon too.
power is not declared in main().
This line
void test use_power()
does not make sense and is invalid, and also has no semicolon.
The a instance in test() defined at the end is local to test() and as such will be deallocated when test() returns. The use_power int, has exactly the same problem and trying to extract it's address from the function is useless because you can't access it after the function has returned.
I have no idea what you were trying to do, but this might be?
#include <stdio.h>
#include <stdlib.h>
struct character {
int *power;
};
/* Decalre the function here, before calling it
* or perhaps move the definition here
*/
void test(struct character *pointer);
/* ^ please */
int
main(void) /* int main() is not really a valid signature */
{
struct character instance;
test(&instance);
if (instance.power == NULL)
return -1;
printf("%d\n", *instance.power);
free(instance.power);
return 0;
}
void
test(struct character *pointer)
{
pointer->power = malloc(sizeof(*pointer->power));
if (pointer->power != NULL)
*pointer->power = 25;
}
Your code seems to be wrong. Your definition for test contains no arguments as
void test ()
{
int use_power = 25;
struct character a;
a.power = &use_power;
}
but your prototype contains one argument
void test (use_power)
which is wrongly put. First there are no semicolons; at the end of your prototype declaration, secondly by looking at your code, use_power is a variable and not a datatype so it cannot be present solely in a function declaration.
You will get an argument mismatch error.
You have used the line in main()
printf("%d\n",*power);
which is absolutely wrong. you cannot access any member of a structure without a structure variable.
And again, you have not mentioned the; after your call to the incorrect test()before this line
As you have not put your question so properly, I must figure out what you wish to achieve. I bet you want to hold the address of a integer in the pointer member of a structure and then print its value.
Below is a code snippet which will work as you desire.
#include <stdio.h>
#include <stdlib.h>
struct character
{
int *power;
};
struct character a; //define a structure variable
void test ();
int main ()
{
test ();
printf("%d\n",*(a.power)); // print the member of structure variable a
return 0;
}
void test ()
{
int use_power = 25;
a.power = &use_power;
}
example
#include <stdio.h>
struct character {
int *power;
};
void test(struct character *var);
int main (void){
struct character use_power;
int power = 5;
use_power.power = &power;
test(&use_power);
printf("%d\n", power);
return 0;
}
void test(struct character *var){
int use_power = *var->power;
*var->power = use_power * use_power;
}
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 ...
I am working in C, and have some variables that I don't want to be global, but I do want to have get and set methods for them that can be accessed "Globaly" outside of the file. I am used to doing this in Java, but C is very different in this manner. Basically I am looking for something that follows this pseudo Code, but I have not been able to find anywhere with examples that I might look at.
main.c
#include data.h
set(b);
datalog.c
#include data.h
get(b);
data.c
private int c;
set(b){
c = b;
}
get(c){
return c;
}
You make the variable static. When a global variable is made static, its scope is restricted to the current file.
An example is as follows:
Filename: main.c
#include <stdio.h>
#include "header.h"
extern int get();
extern void set(int);
int main()
{
set(10);
printf("value = %d \n", get());
set(20);
printf("value = %d \n", get());
set(30);
printf("value = %d \n", get());
set(40);
printf("value = %d \n", get());
return 0;
}
Filename: header.h
#include <stdio.h>
int get(void);
void set(int);
Filename: header.c
#include "header.h"
static int value = 0;
int get(void)
{
return value;
}
void set(int new_value)
{
value = new_value;
}
Output:
$ gcc -Wall -o main main.c header.h header.c
$ ./main
value = 10
value = 20
value = 30
value = 40
$
If you want private variables in c, there are a number of techniques that can approximate a private variable, but the C language actually doesn't have a "protection" concept that extends to private, public, protected (as C++ does).
C will show the name of any variable (it's a requirement in C) so you must approach it with the idea of information hiding the type of the variable (making dereferencing quite difficult).
One trick is to define the variable as an void* with the actual variable type being known in only one .c module.
/* somefile.h */
extern void* counter;
/* somefile.c */
#include "somefile.h"
int actualCounter = 0;
void* counter = &actualCounter;
/* otherfile.c */
#include "somefile.h"
// we can see "counter", but we cannot "use" it here; because we don't have access
// to the real "hidden" type of "int".
A better method is to extend this idea using the struct keyword, and make pseudo-methods, like so
/* person.h */
struct s_person;
typedef Person struct s_person;
Person* new_Person(char* name);
void delete_Person(Person* person);
void Person_setName(Person* person, char* name);
char* Person_getName(Person* person);
/* person.c */
struct s_person {
char* name;
};
Person* new_Person(char* name) {
Person* object = (Person*)malloc(sizeof(struct s_person));
// duplicate the string for more security, otherwise constructor
// could manipulate the "private" string after construction.
object->name = strdup(name);
return object;
}
void delete_Person(Person* person) {
// some implementations pass a Person** to set the reference to 0
// this implementation requires that the caller sets his own references to 0
free(person->name);
free(person);
}
void Person_setName(Person* person, char* name) {
// free the old
free(person->name);
// duplicate the new to provide "out of simulated class" modification by malicious
// name setter.
person->name = strdup(name);
}
char* Person_getName(Person* person) {
// must return a copy, otherwise one can manipulate name
// from reference provided by Person_getName(...);
return strdup(person->name);
}
/* otherfile.c */
#include "Person.h"
/* Now we can hold Person "simulated objects", but we cannot */
/* manipulate their "state" without using the C simulated object */
/* methods */
int main(int argc, char** argv) {
Person* bob = new_Person("bob");
printf("%s\n", Person_getName(bob));
delete_Person(bob);
// critical or we hold a pointer to freed memory.
bob = 0;
return 0;
}
Techniques like this have several variants, one is to have a "public struct" with a void* pointer to the "private struct". One is to include the "methods" as function pointers in the "public struct" (a step towards supporting polymorphism), one is to actually write a full and proper C++ type system which attempts to resolve things exactly as C++ would (class hierarchies, polymorphisim, late binding, information hiding, etc).
Basically, you can get some "object-oriented-ness" without too much work, but as you add more features of -ornamentation, you will add more glue code (until it is much simpler to actually use an object-oriented programming language).
You can type:
static int c;
This way, the ".o" won't export the "c" variable.
By your example, you can try using some struct with this information. A struct is like a class with only public member variables (i.e. no functions). So consider something as follows
#include <stdio.h>
typedef struct _somestruct
{
int c;
} theStruct;
int getC(theStruct* obj)
{
if(obj == NULL)
return -1;
return obj->c;
}
void setC(theStruct* obj, int val)
{
if(obj == NULL)
return;
obj->c = val;
}
int main()
{
theStruct myStruct;
setC(&myStruct, 5);
printf("%d\n", getC(&myStruct));
return 0;
}
As you can see, C works only with objects and functions. But to get a global variable across all files, try static int c = 0;
The example above is nearly as close as you can possibly get to a "java-style" convention.
static int c;
int get(void) {
return c;
}
int set(int n) {
c = n;
}
You can improve on #RageD's answer by using function pointers:
#ifndef MYCLASS_H
#define MYCLASS_H
/********************************* MyClass.h **********************************/
// Typedef function pointers for usage clarity
typedef int (*GetInt)();
typedef void (*SetInt)();
typedef struct MyClass {
int Value;
GetInt GetValue;
SetInt SetValue;
} MyClass_t;
// Make the default class accessible to other modules
extern MyClass_t new_MyClass;
#endif
/********************************* MyClass.c **********************************/
#include <stdio.h>
static int getValue(MyClass_t* obj){
if(obj == NULL)
return -1;
return obj->Value;
}
static void setValue(MyClass_t* obj, int value){
if(obj == NULL)
return;
obj->Value = value;
}
// Default "constructor" of MyClass
MyClass_t new_MyClass = {0, &getValue, &setValue};
/*********************************** main.c ***********************************/
//#include "MyClass.h"
int main(){
// Create a default instance of the class
MyClass_t myClass = new_MyClass;
// Call the private (static) Getter function --> Prints 0
printf("%d\n", myClass.GetValue(&myClass));
// Set the instance's value by the Setter function
myClass.SetValue(&myClass, 9);
// Prints 9
printf("%d\n", myClass.GetValue(&myClass));
return 0;
}
I'm new to C and I have a function that calculates a few variables. But for now let's simplify things. What I want is to have a function that "returns" multiple variables. Though as I understand it, you can only return one variable in C. So I was told you can pass the address of a variable and do it that way. This is how far I got and I was wondering I could have a hand. I'm getting a fair bit of errors regarding C90 forbidden stuff etc. I'm almost positive it's my syntax.
Say this is my main function:
void func(int*, int*);
int main()
{
int x, y;
func(&x, &y);
printf("Value of x is: %d\n", x);
printf("Value of y is: %d\n", y);
return 0;
}
void func(int* x, int* y)
{
x = 5;
y = 5;
}
This is essentially the structure that I'm working with. Could anyone give me a hand here?
You should use *variable to refer to what a pointer points to:
*x = 5;
*y = 5;
What you are currently doing is to set the pointer to address 5. You may get away with crappy old compilers, but a good compiler will detect a type mismatch in assigning an int to an int* variable and will not let you do it without an explicit cast.
void function(int *x, int* y) {
*x = 5;
*y = 5;
}
would change the values of the parameters.
In addition to the changes that the other posters have suggested for your function body, change your prototype to void func(int *,int *), and change your function definition (beneath main) to reflect void as well. When you don't specify a return type, the compiler thinks you are trying to imply an int return.
You can't forward declare func(int,int) when in reality it is func(int*, int*). Moreover, what should the return type of func be? Since it doesn't use return, I'd suggest using void func(int*, int*).
You can return a single variable of a struct type.
#include <stdio.h>
#include <string.h>
struct Multi {
int anint;
double adouble;
char astring[200];
};
struct Multi fxfoo(int parm) {
struct Multi retval = {0};
if (parm != 0) {
retval.anint = parm;
retval.adouble = parm;
retval.astring[0] = parm;
}
return retval;
}
int main(void) {
struct Multi xx;
if (fxfoo(0).adouble <= 0) printf("ok\n");
xx = fxfoo(42);
if (strcmp(xx.astring, "\x2a") == 0) printf("ok\n");
return 0;
}