I have :
typedef struct a{
int var;
}aa;
typedef struct b{
aa *a;
}bb;
int main()
{
bb *b;
b->a->var;
return 0;
}
struct a nested in b.
How to initialize value for variable var using 2 pointers like this:
b->a->var;
?
Initialize b to a valid pointer.
Initialize b->a to a valid pointer.
Initialize b->a->var.
#include <stdlib.h>
typedef struct a{
int var;
}aa;
typedef struct b{
aa *a;
}bb;
int main(void)
{
bb *b;
/* initialize b */
b = malloc(sizeof(*b));
if (b == NULL) return 1;
/* initialize b->a */
b->a = malloc(sizeof(*b->a));
if (b->a == NULL)
{
free(b);
return 1;
}
/* initialize b->a->var */
b->a->var = 42;
/* free what are allocated */
free(b->a);
free(b);
return 0;
}
Struct a is not nested in struct b, but struct b contains a pointer to a a struct a object.
The two objects' pointers can be initialized independently E.g.: First allocate memory for a, then allocate memory for b, and finally assign the memory allocated for a to b->a.
However, it would be better to allocate memory for b first:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int var;
} aa;
typedef struct {
aa *a;
} bb;
int main() {
bb *b = (bb*) malloc(sizeof *b);
b->a = (aa*) malloc(sizeof *(b->a));
b->a->var = 5;
printf("%d\n", b->a->var);
free(b->a);
free(b);
}
(Checking malloc's return values omitted for brevity.)
Note the free'ing of memory in the reverse order. If b would have been free'd first, the pointer to a would have been lost.
Also, note how the typedef's do not declare an additional unused struct a and struct b.
Related
I am having a problem with pointers.
this is an example of what I want
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book b[10]; //Array of structure variables
struct Book* p; //Pointer of Structure type
p = &b; --- HERE is the ERROR
}
This is the error part
p = &b;
b is an array, which can itself decay into a pointer variable. By writing &b, you actually take the address of that pointer and then you end up with pointer to a pointer. It is enough to just write p = b.
Try this. I have not checked but this should work.
p = b;
now if you want to iterate you array of structure then do this
// Example program
#include <stdio.h>
struct Book
{
char name[10];
int price;
};
int main()
{
struct Book b[10]; //Array of structure variables
struct Book* p; //Pointer of Structure type
p = b;
int i = 0;
for(i = 0 ; i<10; i++)
{
printf("Price : %d\n", (p+i)->price);
}
}
b itself is a pointer. Here you can think of arrays as of pointers. So use p=b instead of p=&b
Hej,
I was wondering , can one get a container of the pointer using macro container_of in linux kernel? Can simmilar macro be used?
F.ex
struct container {
int a;
struct *b;
};
Having *b how can obtain *container?
Thank you
b is a pointer to some random address independent of the container, you need to pass a pointer to pointer and then use offsetof:
#include <stdio.h>
#include <stddef.h>
struct item {
int c;
};
struct container {
int a;
struct item *b;
};
#define item_offset offsetof(struct container, b)
void fn(struct item **b)
{
struct container *x = (struct container *)((char *)b - item_offset);
printf("b->container->a = %d, b->c = %d\n", x->a, x->b->c);
}
int main(void)
{
struct container x;
struct item b = {20};
x.a = 10;
x.b = &b;
fn(&x.b);
return 0;
}
I would like to allocate memory for arrays that are members of a struct I need to use, inside a function that takes the struct as an argument.
arg->A.size=(int*) malloc(N*sizeof(int));
will not compile (request for member 'size' is something not a structure.
arg->A->size=(int*) malloc(N*sizeof(int));
will throw a segmentation fault error
Any help will be appreciated.
Here is the code, thanks:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// struct A
struct A {
int dim; // dimensions
int* size; // points per dim array
double* val; // values stored in array
int total; // pow(size,dim)
};
// struct B that uses A
struct B {
int tag;
struct A* A;
};
int function_AB(struct B* B);
int main(void){
struct B B;
function_AB(&B);
return 0;
}
int function_AB(struct B* arg){
int N=10;
arg->tag=99;
printf("tag assigned = %d \n", arg->tag);
arg->A->size=(int*) malloc(N*sizeof(int));
return 0;
}
You simply haven't allocated memory for struct A *A. Before assigning anything to A->size you would first need to do something like
B->A = malloc(sizeof(struct A));
The second case is correct, but crashes because the A inside the B declared in main has not been assigned a value. You probably want something like
struct A A;
struct B B;
B.A = &A;
function_AB(&B);
When you have structure pointer in another structure, first you need to allocate memory for that. then allocate the memory for structure members!
struct B {
int tag;
struct A* A;
};
Here A is a pointer to a structure called A. First allocate memory for this, then allocate memory for the elements of struct A
arg->A = malloc(sizeof(struct A));
then do-
arg->A->size = malloc(N*sizeof(int));
Try the following changes in your int function_AB(struct B* arg)-
int function_AB(struct B* arg){
int N=10;
arg->tag=99;
printf("tag assigned = %d \n", arg->tag);
arg->A = malloc(sizeof(struct A)); // First allocate the memory for struct A* A;
arg->A->size = malloc(N*sizeof(int)); // Allocate the memory for struct A members
arg->A->val = malloc(N*sizeof(double));
// do your stuff
// free the allocated memories here
free(arg->A->size);
free(arg->A->val);
free(arg->A);
return 0;
}
And don't cast the result of malloc()!
I have the following code:
#include <stdlib.h>
#include <stdio.h>
struct B
{
int _arr[5];
};
struct A
{
struct B *_pb_arr;
};
int main()
{
int i,j;
struct B b;
struct B *pb = (struct B*)malloc(sizeof (struct B));
*pb = b;
struct A a;
a._pb_arr = (struct B*)malloc(sizeof (struct B)*2);
a._pb_arr[0] = b; //first question
a._pb_arr[1] = *pb; //second question
for (i=0;i<2;++i)
{
for (j=0;j<5;++j)
{
a._pb_arr[i]._arr[j] = i;
}
}
struct A a2 = a;
for (i=0;i<2;++i)
{
for (j=0;j<5;++j)
{
printf ("%d, ", a2._pb_arr[i]._arr[j]);
}
}
return 0;
}
My question is: why on: a._pb_arr[0] = b;
The assignment is on stack.
and on the next line: a._pb_arr[1] = *pb
The assignment is on the heap?
It seems like a.pb_arr was allocated on the heap and each assignment is on the heap also.
Assignments aren't on the stack or heap, objects are.
Object a is on the stack because it's created like this:
struct A a;
To create objects on the heap, you have to allocate memory for them using malloc.
So although a is on the stack, a._pb_arr will be on the heap. You have to explicitly free the memory when you're done. Following the same reasoning, b is on the stack and pb is on the heap.
When you assign the objects in the array a._pb_arr, the values will be copied, but they still remain on the heap, since you allocated memory to a._pb_arr.
To prevent memory leaks, you have to use free for both a._pb_arr and pb.
#include "stdafx.h"
#include <stdio.h>
struct s
{
char *st;
struct s *sp;
};
struct s *p1,*p2;
void swap(struct s *p1,struct s *p2);
int main()
{
int i;
struct s *p[3];
static struct s a[]={
{"abc",a+1},{"def",a+2},{"ghi",a}
};
for(i=0;i<3;i++)
{
p[i]=a[i].sp;
}
swap(*p,a);
printf("%s %s %s\n",p[0]->st,(*p)->st,(*p)->sp->st);
return 0;
}
void swap(struct s *p1,struct s *p2)
{
char *temp;
temp = p1->st;
p1->st = p2->st;
p2->st = temp;
}
This program outputs as abc,abc,ghi. My doubt is what does p[0]->st,(*p)->st,(*p)->sp->st outputs.we havent intialised st with abc or ghi.How does it outputs the string?
We havent intialised st with abc or ghi. How does it outputs the
string?
The value of the st member for each structure in the statically allocated array a is actually initialized through an initialization list. Writing
static struct s a[]={
{"abc",a+1},{"def",a+2},{"ghi",a}
};
has the same effective meaning after its execution as writing the following:
static struct s a[3];
a[0].st = "abc";
a[0].sp = a+1;
a[1].st = "def";
a[1].sp = a+2;
a[2].st = "ghi";
a[2].sp = a;
And what's effectively happened after both methods of initialization is you have a statically-allocated circular linked list of struct s, where the data-members of each node in the list (the st member) is pointing to a string literal like "abc", "def", etc. The sp data member is pointing to the next node in the linked list.
I haven't analysed all the statements, but assignment to ->st and ->sp happens here:
static struct s a[]={
{"abc",a+1},{"def",a+2},{"ghi",a}
};
the rest are games with pointers so the output is what you see. So, say:
the a array is created and initialized;
in the for loop the p array is also initialized;
noticing that sp recursively points to struct s instances, p and a have the same structure;
each elements of p is made point to a struct s instance taken from one of the elements of a.