I wanted to create a simple program to better understand how the pointers work and I came across a problem. I want to work on 3 files main.c modul.c and modul.h.
modul.h
typedef struct
{
int data;
}w_options;
int show(); //prototype of function
modul.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "modul.h"
int show()
{
w_options *color;
color = (w_options *)malloc(sizeof(w_options));
printf("%d\n", color->data);
if (color->data == 1)
{
printf("Good\n");
}
else
{
printf("Bad\n");
}
}
main.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "modul.h"
int main()
{
w_options *color;
color = (w_options *)malloc(sizeof(w_options));
color->data=1;
printf("%d\n", color->data);
show();
}
In main.c I am setting the value of color->data to 1 and it's working, it's printing 1. But I would like to pass this set value to modul.c. That's way I created simple if instruction to check if the value is passed. Unfortunately the value isn't passed and I don't have idea how to fix it. I need this kind of solution for my bigger program.
The Output:
1
0
Bad
You just have to pass it as an argument to your function. And, as your function returns nothing, declare it as void.
modul.h
typedef struct
{
int data;
}w_options;
void show(w_options *color); //prototype of function
modul.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "modul.h"
void show(w_options *color)
{
if (color->data == 1)
{
printf("Good\n");
}
else
{
printf("Bad\n");
}
}
main.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "modul.h"
int main()
{
w_options *color;
color = (w_options *)malloc(sizeof(w_options));
color->data=1;
printf("%d\n", color->data);
show(color);
return EXIT_SUCCESS;
}
Currently you aren't passing any values.
In modul.c you're creating one pointer named color that has no initialized values, you are only allocating memory.
color = (w_options *)malloc(sizeof(w_options));
printf("%d\n", color->data);
It's an accident that it happens to print 0 as the current value. This isn't guaranteed at all.
In main.c you're creating another different pointer, also named color but in a different scope, whose own color->data is set to 1.
color = (w_options *)malloc(sizeof(w_options));
color->data=1;
printf("%d\n", color->data);
This correctly prints 1 as the current value because you've initialized it properly.
If you want show to use a pointer, pass the pointer to it as an argument and use it on the other end.
main.c
...
show(color);
...
modul.c
...
int show(w_options *color)
{
// this is a parameter now, receiving the value from its caller
//w_options *color;
//color = (w_options *)malloc(sizeof(w_options));
printf("%d\n", color->data);
if (color->data == 1)
{
printf("Good\n");
}
else
{
printf("Bad\n");
}
}
...
Related
I'm trying to get a struct variable from another file in c. But when I do define a variable inside of other file and trying to printing this variable in main file it didn't work.
Main File
#include <stdio.h>
#include <stdlib.h>
#include "tesst.h"
int main()
{
struct tst t;
this_test(t);
printf("%s", t.string);
return 0;
}
Other File Header
#ifndef _TESST_H
#define _TESST_H
struct tst
{
char *string;
};
void this_test(struct tst t);
#endif
Other File
#include <stdio.h>
#include <stdlib.h>
#include "tesst.h"
void this_test(struct tst t)
{
t.string = "this is test";
}
When I tried to execute this program it print nothing. How can I solve this problem?
The structure passed as a parameter to the function is only a copy. To modify the structure of the main function in the this_test function, you must pass its address. It's like the scanf function where you have to pass the address of the variables you want to modify.
#include <stdio.h>
struct tst
{
char *string;
};
void this_test(struct tst *t)
{
t->string = "this is test";
}
int main()
{
struct tst t;
this_test(&t);
printf("%s", t.string);
return 0;
}
I am trying to create a simple ADT using a structure that takes 2 dates. Then returns an age. It must use a Header file, a source file for the Header file, and a main file.
This is what I have it runs and nothing happens. Can someone tell me what i am doing wrong?
age.h
#ifndef AGE_H_
#define AGE_H_
typedef struct getage * Age;
#define MAX 5
Age get_Age(int birthYear, int yearNow);
void age_Destroy(Age a);
#endif
age.c
#include <stdio.h>
#include "age.h"
struct getage {
int birthYear;
int yearNow;
};
Age a[1];
Age get_Age(int birthYear, int yearNow){
int giveAge = 0;
giveAge = a[0]->yearNow - a[0]->birthYear;
printf("%d",giveAge);
return 0;
}
void age_Destroy(Age a){
free(a);
}
main.c
#include <windows.h>
#include <stdio.h>
#include "age.h"
void age_print(Age a);
void age_print(Age a){
printf("%d\n", &a);
}
int main() {
Age a;
get_Age(1986, 2020);
age_print(a);
printf("%d\n", &a);
system("pause");
//age_Destroy(a);
}
What are wrong:
In the function get_Age:
Instead of allocating structures, a[0] (global variable, initialized to NULL) is dereferenced.
0 (converted to NULL) is returned instead of returning an age.
In the function age_Destroy:
free() is used without declaration nor including proper header.
In the function age_print:
Data having wrong type is passed to printf(): %d requests int but Age* is passed.
In the function main:
The return value of get_Age is dropped.
Data having wrong type is passed to printf(): %d requests int but Age* is passed.
Fixed code that won't cause Segmentation Fault nor undefined behavior:
age.h (not changed)
#ifndef AGE_H_
#define AGE_H_
typedef struct getage * Age;
#define MAX 5
Age get_Age(int birthYear, int yearNow);
void age_Destroy(Age a);
#endif
age.c
#include <stdio.h>
#include <stdlib.h> // for malloc() and free()
#include "age.h"
struct getage {
int birthYear;
int yearNow;
};
Age get_Age(int birthYear, int yearNow){
Age a = malloc(sizeof(*a)); // allocate a structure
if (a == NULL) { perror("malloc"); exit(1); }
a->yearNow = yearNow; // assign data
a->birthYear = birthYear;
int giveAge = 0;
giveAge = a->yearNow - a->birthYear;
printf("%d",giveAge);
return a; // return pointer to the allocated structure
}
void age_Destroy(Age a){
free(a);
}
main.c
#include <stdlib.h> // more portable header for system()
#include <stdio.h>
#include "age.h"
void age_print(Age a);
void age_print(Age a){
printf("%p\n", (void*)a); // use valid combination of format and data
}
int main() {
Age a;
a = get_Age(1986, 2020); // assign the return value
age_print(a);
printf("%p\n", (void*)a); // use valid combination of format and data
system("pause");
age_Destroy(a); // enable freeing
}
(Some behavior may look weird, but I believe this is valid because not desired behavior is described.)
How can I do global constant initialization like this? Is it possible at all? Or there is another way to do what I want? I mean I need global parameters gained from main() and they must be constants.
#include <stdio.h>
#include <stdlib.h>
const int var;
int main(int argc, char *argv[]) {
var = atoi(argv[1]);
/* ... */
return 0;
}
I need global parameters gained from main() and they must be constants.
No portable way to do directly as OP wants.
Code needs different access for reading and writing. Effectively hiding the access to the true data.
A close solution it to set and get data via functions defined in another file. Then no way to change data once set and only settable once.
main_var.h
int main_var_get(void);
void main_var_set(int v);
main_var.c
#include <stdlib.h>
#include "main_var.h"
static int var; // This could instead be a struct of many members.
// Or a pointer to a struct with many members.
static int var_init;
int main_var_get(void) {
if (!var_init) {
// Handle call of get before set, perhaps exit or return default value
exit(EXIT_FAILURE);
}
return var;
}
void main_var_set(int v) {
if (var_init) {
// Handle 2nd set, perhaps exit or ignore
exit(EXIT_FAILURE);
}
var = v;
var_init = 1;
}
main.c
#include <stdio.h>
#include "main_var.h"
int main(void) {
main_var_set(42);
...
printf("%d\n", main_var_get());
}
Another is to use a const int *. Access before setting is the same no-no as dereferencing NULL. Attempting to write *main_var_addr is UB like writing any const object.
main_var.h
extern const int *main_var_addr;
void main_var_set(int v);
main_var.c
#include <stdlib.h>
#include "main_var.h"
const int *main_var_addr = NULL;
static int var;
void main_var_set(int v) {
if (main_var_addr) {
// Handle 2nd set attempt, perhaps exit or ignore
exit(EXIT_FAILURE);
}
var = v;
main_var_addr = &var
}
main.c
#include <stdio.h>
#include "main_var.h"
int main(void) {
main_var_set(42);
...
printf("%d\n", *main_var_addr);
}
I don't think C allows you to initialize a constant variable elsewhere. However, you can just change var from const to static.
This is not possible, actually const doesn't mean the variable is constant in C, it's only mean that you are not allowed to change the value of the variable, but someone else could.
Global value are initialize before the main run, that mean you can't initialize at runtime, how this initialization is done is implementation behavior so there is no "pure C" way to do what you ask.
However, I don't see why you could not encapsulate your global:
my_var.h:
int init_my_var(int argc, char **argv);
int get_my_var(void);
my_var.c
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
static int var;
int init_my_var(int argc, char **argv) {
#ifndef NDEBUG
#include <stdbool.h>
#include <assert.h>
{
static bool first = true;
assert(first);
first = false;
}
#endif
if (argc < 2) {
return 1;
}
errno = 0;
long ret = strtol(argv[1], NULL, 10);
if (errno || (ret < INT_MIN || ret > INT_MAX)) {
return 2;
}
var = (int)ret;
return 0;
}
int get_my_var(void) {
return var;
}
main.c:
#include <stdio.h>
int main(void) {
printf("%d\n", get_my_var());
if (init_my_var(2, (char *[]){"", "42"})) {
return EXIT_FAILURE;
}
printf("%d\n", get_my_var());
if (init_my_var(2, (char *[]){"", "0"})) {
return EXIT_FAILURE;
}
}
i want to assign value of an integer array to integer pointer. The pointer takes a different value of assignment. Please help me on this.
I have assigned 2 for port_val variable. But, after assigning that to ofport_request var, the value becomes different.
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
int main ()
{
printf("INSIDE MAIN..\n");
int64_t of_port[100];
int count=2;
int i;
int port_val = 2;
int port_next_val = 4;
size_t n_ofport_request = 1;
int64_t *ofport_request = malloc(sizeof *ofport_request * (n_ofport_request));
for(i=0;i<count;i++) {
if(i == 0) {
of_port[i] = port_val;
} else {
of_port[i] = port_next_val;
}
ofport_request[0] = of_port[i];
printf("OFPORT VAL = %d\n",ofport_request);
}
return 0;
}
If you want to print the pointer variable, you have to use the * before the variable name.
Use the below printf statement it will work.
printf("OFPORT VAL = %lld\n",*ofport_request);
I have a header file (generalfunctions.h):
#ifndef GENERALFUNCTIONS_H
#define GENERALFUNCTIONS_H
//functionsdeclartion for example
int getInt(char* text);
#endif /* GENERALFUNCTIONS_H */
and a C file generalfunctions.c where I include this headerfile (so I can use some of the functions within each other and don't have bother with their order) and code out the functions.
generalfunctions.c:
#include "generalfunctions.h"
#include <stdlib.h>
#include <stdio.h>
//functions implentaion for example
int getInt(char* text){
int i;
printf("%s\n", text);
if(scanf("%d", &i)==EOF){
printf("INT_ERROR\n");
exit(1);
}
while (fgetc(stdin) != '\n');
return i;
}
//...
Now I need some of these functions in a file called project_objects.c that together with project_objects.h defines a couple of structs, unions, variables and functions with these things I need for my project.
project_objects.h:
#ifndef POINT_H
#define POINT_H
typedef struct point{
int x;
int y;
} point;
point create_point(void);
void print_point(point *p);
//...
#endif /* POINT_H */
project_objects.c:
#include <stdlib.h>
#include <stdio.h>
#include "project_objects.h"
#include "generalfunctions.h"
point create_point(void){
point p;
p.x=getInt("Give my a x");
p.y=getInt("Give my a y");
return p;
}
void print_point(point *p){
printf("x: %d\n", p->x);
printf("y: %d\n", p->y);
}
//..
However I also need some of the functions described in generalfunctions.h directly in my main program:
#include "generalfunctions.c"
#include "project_objects.c"
#include <stdlib.h>
#include <stdio.h>
int main(void){
int i=getInt("How many points would you like to create?");
while(i<1){
i=getInt("Cannot create a negative number of points. How many points would you like to create?");
}
point pointarray[i];
for(int j=0; j<i; j++){
pointarray[j]=create_point();
}
for(int k=0; k<i; k++){
printf("Point %d:\n", k+1);
print_point(pointarray+k);
}
return EXIT_SUCCESS;
}
This seems to work. If I just include the h-files than I get the error that getInt() isn't defined when I link. And before when I included the C file for general functions in project_object.c I got errors for duplication. But now the files seem more dependent on each other than I planned. I also don't understand why this works.
Do not include .c-files. Write function protytypes in .h-files and include them.
project_object.h
typedef int faa;
foo.h
include "project_object.h"
faa foo( faa x ); // prototype for function "foo"
foo.c
#include "foo.h"
faa foo( faa x ) // implementation of function "foo"
{
return x + 666;
}
main.c
#include "project_object.h"
#include "foo.h" // include .h-file with prototype of function "foo"
int main( void )
{
faa x;
x = foo(0); // call function "foo"
return 0;
}