i can't assign one struct to another in c - c

i have 2 structs, i want to assign one struct to another, but when i print the results, it prints crap, the functions : "ver_tope" is on charge to do that , what am i doing bad?, here is the code:
#include <stdio.h>
#include <stdlib.h>
#define TAM 4
typedef struct{
char nomyap[40];
int edad;
}t_info;
typedef struct {
t_info pila [TAM];
int tope;
}t_pila;
void ver_tope(const t_pila *p, t_info *d);
int main()
{
t_pila pila;
t_info info;
//I CHARGE BOTH STRUCTS
ver_tope(&pila, &info);
return 0;
}
void ver_tope(const t_pila *p, t_info *d)
{
*d = p->pila[(p->tope)-1];
return ;
}

Try adding an initialisation for pila.tope in main() ex:
... //I CHARGE BOTH STRUCTS
pila.tope =2;
ver_tope(&pila, &info);
...
That stopped the segmentation fault...

int main()
{
t_pila pila;
t_info info;
ver_tope(&pila, &info);
return 0;
}
You have not initialized either variable. Since pila is the source of the assignment you can do the following:
int main()
{
t_pila pila = { 0 };
pila.tope = 1;
t_info info;
ver_tope(&pila, &info);
return 0;
}
Here I default initialized pila and then set its tope member to 1. I did not initialize info since ver_tope assigns to it. It would be clearer if you converted ver_tope into a function that returned t_info.

Related

initialise constructor values of structure using pointer in c [duplicate]

This question already has answers here:
How do malloc() and free() work?
(13 answers)
Closed 3 years ago.
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char name[50];
int year_of_birth;
char sex[7];
char father[50];
char mother[50];
char significant_other[50];
char children[50];
};
struct Person* person_constructor(char *name, int year_of_birth, char *sex);
int main(){
struct Person* p1 = person_constructor("Abbas", 1970, "male");
}
struct Person* person_constructor(char *name, int year_of_birth, char *sex) {
struct Person *p;
printf("%s",*name);
printf("%s",*sex);
printf("%d",&year_of_birth);
// how to initalise these here and return name, age and sex everytime , can you tell me in print function
}
i want to do :
Person* person_constructor(char *name, int year_of_birth, char *sex);
A person with the given arguments and return it.
Also allocate memory.
In example code bellow you can find one of possible solutions to your question.
In C language is not possible to return more then one variable, but you can return pointer to constructed structure object and access structure members using notation stuct_ptr->struct_member.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char name[50];
int year_of_birth;
char sex[7];
char father[50];
char mother[50];
char significant_other[50];
char children[50];
};
struct Person* person_constructor(char *name, int year_of_birth, char *sex);
int main(){
struct Person* p1 = person_constructor("Abbas", 1970, "male");
/* it is not possible to return more variables in C */
/* you can use pointer to access members from constructed structure: */
printf("print from main:\n %s %d %s \n", p1->name, p1->year_of_birth, p1->sex);
if( p1 != NULL) free(p1); /* do not forget do deallocate something taht is allocated */
return 0;
}
struct Person* person_constructor(char *name, int year_of_birth, char *sex) {
struct Person *p = calloc(1, sizeof(struct Person));
if( p == NULL ) return p; /* memory alocation failed! */
strcpy(p->name, name);
p->year_of_birth = year_of_birth;
strcpy(p->sex, sex);
printf("print from constructor:\n");
printf("%s ",p->name);
printf("%s ",p->sex);
printf("%d \n",p->year_of_birth);
return p;
}

How to pass the variable address of the structure short name to a function

How can I pass the variable address of the structure short name (color) to a function (fun) arguments.
#include <stdio.h>
void fun();
struct figure {
char name[30];
float field;
} color;
int main(void) {
fun();
return 0;
}
How to pass the variable address of the structure short name
To pass the address you only need &color.
Then the function needs to accept a pointer to struct figure.
It may look like:
#include <stdio.h>
#include <string.h>
struct figure{
char name[30];
float field;
} color;
void fun(struct figure *); // Function takes pointer to struct figure
int main(void){
strcpy(color.name, "Joe"); // Initialize color
color.field = 42.0;
fun(&color); // Pass address of color
return 0;
}
void fun(struct figure *c)
{
printf("%s\n", c->name); // Access color using the passed pointer
printf("%f\n", c->field);
}
Output:
Joe
42.000000
struct figure { ... }; would just introduce a new type named struct figure, whereas struct figure { ... } color; does two things (1) introduce above mentioned type and (2) define a variable named color of that type.
To pass an object of type struct figure to a function, write...
struct figure{
char name[30];
float field;
} color;
void fun(struct figure f) {
printf("%s %f\n", f.name, f.field);
}
int main(void){
struct figure myObj;
strcpy(myObj.name, "Hello!");
myObj.field = 1.0;
fun(myObj);
return 0;
}
You could also pass the address of such an object, which would then allow the function to alter the originally passed object as well:
void fun(struct figure *f) {
f->field = 2.0
printf("%s %f\n", f->name, f->field);
}
int main() {
...
fun(&myObj);

Extract sub struct from main struct for thread creation

I am having issues trying to send multiple arguments to the pthread_create, the issue is basically because one of the arguments is another struct.
This is the node.
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#define NUM_THREADS 4
struct arr {
char line[10];
};
struct args {
struct arr record; int count; int init; int end;
};
void* processarr(void *arguments)
{
int count; int init; int end;
struct args *argstmp=arguments;
init=argstmp->init;
count=argstmp->count;
end=argstmp->end;
struct arr record[count];
record=(struct arr)argstmp->record;
printf("Some of the vals are init %d count %d end %d\n",init, count, end);
printf("vals like record 0\n", record[0].line);
pthread_exit(NULL);
}/*end of processarr*/
int main (int argc, char *argv[])
{
int line_count;
FILE *ptr_file;
char buf[10];
ptr_file =fopen(argv[ 1 ],"r");
if (!ptr_file)
return 1;
while (fgets(buf,10, ptr_file)!=NULL)
{
line_count++ ;
}
rewind(ptr_file);
struct arr record[line_count];
line_count=0;
while (fgets(buf,10, ptr_file)!=NULL)
{
line_count++ ;
buf[strcspn(buf, "\r\n")] = 0; /* Removing end null chars*/
strcpy(record[line_count].line,buf);
}
float grptmp,group, lgroup;
grptmp=line_count/NUM_THREADS;
int counter1,counter2,init,end;
counter2=1;
struct args myargs;
//processarr(record, line_count, init, end);
pthread_t threads[NUM_THREADS];
for (counter1=0;counter1<=line_count;counter1++)
{
if(counter2==NUM_THREADS)
{
end=line_count;
}else{
end=counter1+grptmp;
}
init=counter1;
myargs.record=*record;
myargs.count=line_count;
myargs.init=init;
myargs.end=end;
printf ("Run job #%d with paramts Init=%d and End=%d\n",counter2, init, end);
//call here
//struct arr *record; int count; int init; int end;
int rc;
long t;
for(t=0;t<NUM_THREADS;t++){
rc = pthread_create(&threads[t], NULL,processarr,&myargs);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
counter1=counter1+grptmp;
counter2++;
}
return 0;
}
So, when I send my arguments,the one stored inside myargs.record=*record, for some reason I am not able to "unpack" it once in the function.
The function is was defined as void to be able to catch the whole big argument, and I am trying to re-map everything there, the counts are working fine, but the one called record, that is actually another struct is not working, looks like a cast issue.
void* processarr(void *arguments)
{
int count; int init; int end;
struct args *argstmp=arguments;
init=argstmp->init;
count=argstmp->count;
end=argstmp->end;
struct arr record[count];
record=(struct arr)argstmp->record;
printf("Some of the vals are init %d count %d end %d\n",init, count, end);
printf("vals like record 0\n", record[0].line);
pthread_exit(NULL);
}
I am getting the following error when compiling.
test4.c: In function processarr:
test4.c:31:7: error: assignment to expression with array type
record=(struct arr)argstmp->record;
Any idea why this is not working? This last one was my last change using the casting (struct arr) in front of the argstmp (which is supposed to have everything inside).
Elaborating a little more on my response, this is what I would do using another struct to pass the arguments.
typedef struct {char line[10];}mystruct;
typedef struct {mystruct struct1;char line[10];}wrapper;
struct wrapper2 {mystruct struct1;char line[10];};
void unwrap(struct wrapper2 args){
printf("val is %s\n",args.line);
mystruct tmp=args.struct1;
printf("val inside structure is %s\n\n", tmp.line);
}
int main ()
{
mystruct names;
strcpy(names.line,"TEST");
struct wrapper2 wrapper1;
wrapper1.struct1=names;
strcpy(wrapper1.line,"Value1");
unwrap (wrapper1);
}
I hope this example helps you fix the issue, you just need to pass the same thing using the pthread_create.
Update:
The final code could look like this:
#include <pthread.h>
#include <stdlib.h>
struct mystruct {
int val;
};
void * func (void *args){
struct mystruct *st1=args;
printf("Thread created..%d\n", st1->val);
pthread_exit(NULL);
}
int main ()
{
/* Thread creation logic as void * (*)(void *)
int pthread_create (pthread_t *, const pthread_attr_t *,
void *(*)(void *), void *);
* */
struct mystruct mystruct1;
mystruct1.val=230;
pthread_t threads;
pthread_create(&threads,NULL,&func,&mystruct1);
pthread_exit(NULL);
return 0;
}
I recommend you read the actual manual of pthread_create.
http://man7.org/linux/man-pages/man3/pthread_create.3.html

Initializing a Struct of a Struct

If I have a struct in C that has an integer and an array, how do I initialize the integer to 0 and the first element of the array to 0, if the struct is a member another struct so that for every instance of the other struct the integer and the array has those initialized values?
Initialisers can be nested for nested structs, e.g.
typedef struct {
int j;
} Foo;
typedef struct {
int i;
Foo f;
} Bar;
Bar b = { 0, { 0 } };
I hope this sample program helps....
#include <stdio.h>
typedef struct
{
int a;
int b[10];
}xx;
typedef struct
{
xx x1;
char b;
}yy;
int main()
{
yy zz = {{0, {1,2,3}}, 'A'};
printf("\n %d %d %d %c\n", zz.x1.a, zz.x1.b[0], zz.x1.b[1], zz.b);
return 0;
}
yy zz = {{0, {0}}, 'A'}; will initialize all the elements of array b[10] will be set to 0.
Like #unwind suggestion, In C all instances created should initialized manually. No constructor kind of mechanism here.
You can 0-initialize the whole struct with {0}.
For example:
typedef struct {
char myStr[5];
} Foo;
typedef struct {
Foo f;
} Bar;
Bar b = {0}; // this line initializes all members of b to 0, including all characters in myStr.
C doesn't have constructors, so unless you are using an initializer expression in every case, i.e. write something like
my_big_struct = { { 0, 0 } };
to initialize the inner structure, you're going to have to add a function and make sure it's called in all cases where the structure is "instantiated":
my_big_struct a;
init_inner_struct(&a.inner_struct);
Here is an alternative example how you would do things like this with object-oriented design. Please note that this example uses runtime initialization.
mystruct.h
#ifndef MYSTRUCT_H
#define MYSTRUCT_H
typedef struct mystruct_t mystruct_t; // "opaque" type
const mystruct_t* mystruct_construct (void);
void mystruct_print (const mystruct_t* my);
void mystruct_destruct (const mystruct_t* my);
#endif
mystruct.c
#include "mystruct.h"
#include <stdlib.h>
#include <stdio.h>
struct mystruct_t // implementation of opaque type
{
int x; // private variable
int y; // private variable
};
const mystruct_t* mystruct_construct (void)
{
mystruct_t* my = malloc(sizeof(mystruct_t));
if(my == NULL)
{
; // error handling needs to be implemented
}
my->x = 1;
my->y = 2;
return my;
}
void mystruct_print (const mystruct_t* my)
{
printf("%d %d\n", my->x, my->y);
}
void mystruct_destruct (const mystruct_t* my)
{
free( (void*)my );
}
main.c
int main (void)
{
const mystruct_t* x = mystruct_construct();
mystruct_print(x);
mystruct_destruct(x);
return 0;
}
You don't necessarily need to use malloc, you can use a private, statically allocated memory pool as well.

Instantiations for structs in C?

So I'm trying to learn C right now, and I have some basic struct questions I'd like to clear up:
Basically, everything centers around this snippet of code:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NAME_LEN 127
const char* getName(const Student* s);
void setName(Student* s, const char* name);
unsigned long getStudentID(const Student* s);
void setStudentID(Student* s, unsigned long sid);
int main(void) {
Student sarah;
const char* my_name = "Sarah Spond";
setName(&sarah, my_name);
printf("Name is set to %s\n", sarah.name);
}
typedef struct {
char name[MAX_NAME_LEN + 1];
unsigned long sid;
} Student;
/* return the name of student s */
const char* getName (const Student* s) { // the parameter 's' is a pointer to a Student struct
return s->name; // returns the 'name' member of a Student struct
}
/* set the name of student s
If name is too long, cut off characters after the maximum number of characters allowed.
*/
void setName(Student* s, const char* name) { // 's' is a pointer to a Student struct | 'name' is a pointer to the first element of a char array (repres. a string)
int iStringLength = strlen(name);
for (i = 0; i < iStringLength && i < MAX_NAME_LEN; i++) {
s->name[i] = name[i];
}
}
/* return the SID of student s */
unsigned long getStudentID(const Student* s) { // 's' is a pointer to a Student struct
return s->sid;
}
/* set the SID of student s */
void setStudentID(Student* s, unsigned long sid) { // 's' is a pointer to a Student struct | 'sid' is a 'long' representing the desired SID
s->sid = sid;
}
However, when I try and compile the program, I get a bunch of errors saying that there's an "unknown type name Student". What am I doing wrong?
Thanks!
Move the type definition for Student - the typedef .. right after #define MAX_NAME_LEN 127, i.e. before it's being referenced.
You need to move the declaration of the Student struct above the first time it is referenced by other code - otherwise those functions will not know what it is.
Struct declarations need to be defined before you use them , so you need to move your Student
As cnicutar said, move the typedef - the reason for this is that the type must be known before it's used. Alternatively, you can forward declare the type.
> Move the typedef .. right after #define MAX_NAME_LEN 127, i.e. before
> it's being used.
OR, if you want to keep your definition after, and if you are ready to use a pointer to Student, you can:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NAME_LEN 127
// forward declare Student ici
struct Student;
//...
// in main, use a pointer to student
int main(void) {
Student *sarah; // Changed to pointer
const char* my_name = "Sarah Spond";
setName(sarah, my_name); // Pass the pointer instead of reference
printf("Name is set to %s\n", sarah->name); // Use the pointer
//....
delete sarah; // delete object when done
}
// Change struct decl to the following // can't explain the diff yet
struct Student {
char name[MAX_NAME_LEN + 1];
unsigned long sid;
};
A basic structure of a C program is:
//======DOCUMENT SECTION=========
//File:test.c
//Author:
//Description:
//...
//================================
//====INCLUDE SECTION=============
#include "lib1"
#include <lib2>
//================================
//========DEFINITIONS SECTION=====
#define TRUE 1
#define FALSE 0
//================================
//========STRUCTURES SECTION======
struct P{
};
//================================
//========TYPEDEFS SECTION========
typedef *P P;
//================================
//========FUNCTION HEADERS========
void foo1(...);
int foo2(...,...,...);
//================================
//=========GLOBAL VARIABLES=======
int GLOBAL_INT;
float GLOBAL_FLOAT;
//================================
//=====MAIN FUNCTION DEFINITION===
void main(void)
{
...
...
...
}
//=================================
//======FUNCTIONS DEFINITION======
void foo1(...)
{
}
int foo2(...,...,...)
{
}
//================================
A main function is where a C program starts. A main function also typically has access to the command arguments given to the program when it was executed.
Usually you have got:
int main(void);
int main();
int main(int argc, char **argv);
int main(int argc, char *argv[]);

Resources