Create structure variables in a loop in c - c

I am trying to create a bunch of struct variables in C.
So lets say I have a for loop which runs 3 times and creates three struct variables.
My question is that why is it creating the variables that reference the same memory location.
Code:
struct arrIndexStruct {
int *arr;
int index;
};
int main() {
int i;
for (i=0; i<3; i++) {
struct arrIndexStruct arrayIndexStruct;
arrayIndexStruct.arr = someArray;
arrayIndexStruct.index = i;
printf("%p\n",(void *)&arrayIndexStruct);
}
}
The output I get is:
0x7ffeed84f690
0x7ffeed84f690
0x7ffeed84f690
Whereas, If I do
struct arrIndexStruct arrayIndexStruct1;
struct arrIndexStruct arrayIndexStruct2;
printf("%p\n",(void *)&arrayIndexStruct1);
printf("%p\n",(void *)&arrayIndexStruct2);
I'll get
0x7ffc484e64d0
0x7ffc484e64e0
What is the difference between the two behaviors and shouldn't for loop have local scope?
Thanks!

The variable is only defined since the first appearance in the code and until the end of its enclosing block. When it reaches end of scope, its original memory can be used anything else.
Specifically in the loop the variables always occupy the same location as it's simply the easiest thing compiler can achieve.
The second case is completely different as the first variable remains defined while the second is introduced. You could get the same address in the following example but it depends on compiler and also debug level, optimization, etc.:
{
struct arrIndexStruct arrayIndexStruct1;
}
{
struct arrIndexStruct arrayIndexStruct2;
}

Related

Struct and segmentation fault in c

I'm currently new to the struct and linked list. I'm trying to put the values of my array arr_dec[4] in a variable. My array is on a struct, and also in my init function. I think my problem is on the display function, in my if loop.
[EDIT] :
Hi, so I think I correctly changed my errors, but I still get a segmentation fault, and really I don't understand why I get it. If you could see what is wrong and how I can correct it it'll be great ! Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct Plane_dec Element;
struct Plane_dec
{
int array_dec[4];
int nbr_var;
struct Plane_dec *head;
struct Plane_dec *next;
};
void init(int nbr_caract) //It's my initialisation function, i want to initialize my linked list.
{
Element *plane_dec = malloc(sizeof(plane_dec));
Element *head = NULL;
Element *next = NULL;
plane_dec->var_num = 0;
plane_dec->arr_dec[0] = 2;
plane_dec->arr_dec[1] = 5;
plane_dec->arr_dec[2] = 1;
plane_dec->arr_dec[3] = 3;
return *head;
}
void display (int nbr)
{
int i = 0, variable = 0;
struct Plane var;
struct Plane_dec *plane_dec;
init(nbr_caract);
for(i = 0; i <4; i++)
{
variable = plane_dec->arr_dec[i];
printf("%d - ", variable);
}
}
int main()
{
int nbr;
prinft("Please select a number : ");
scanf("%d", &nbr);
display(nbr);
return 0;
}
My output is just : Segmentation fault (core dumped).
Among other problems that prevent compilation:
In display, you pass an uninitialized pointer to a pointer of Plane_dec (you declare a pointer and then pass its address) to init (which is stated to expect just a pointer!), and then within init you attempt to modify its fields.
If what you've been meaning to do is dynamically allocate a Plane_dec, then you need to actually do so: init needs to begin with a *plane_dec = malloc(...), and you need to modify its declaration to accept a pointer to a pointer to Plane_dec, and not just a pointer to Plane_dec.
If, on the other hand, what you've been meaning to do is just modify a local variable declared within display and then discard it when display finishes its run, then you don't want display's plane_dec to be a pointer (so remove the asterisk from the variable declaration).
Either way, the arr_dec you declare within init gets promptly discarded and doesn't have anything to do with the similarly-named field of the plane_dec variable, and nbr_var also doesn't do anything, as it is. (Also note that in display you attempt to access the arr_dec field of Plane_dec, but the field is named array_dec, not arr_dec.)
If this doesn't solve your problem, please make sure to provide more context about what you've actually been meaning to do, as well as post your error (textually, not as an image), and create a minimal reproducible example: make sure to copy the code in question into a brand new file and test that it compiles, and provide the error details based on that. It is quite likely that if you do all of this, you'll figure out the answers on your own; and if you don't, we'll be able to help a lot more efficiently.

C error: type name requires a specifier or qualifier

I tried to create a struct that would incude a dynamic array:
typedef struct
{
int idNode;
int* n; //pointer to the int nodes in the dynamically created array of nodes
n = calloc(MAX, sizeof(int)); //dynamic array to store the loser member of the pair
int counter = 0;
}
node;
But I get
error: type name requires a specifier or qualifier
You cannot assign a value to n in the struct declaration. You need to provide a function (something like a constructor ;-) that initializes the structure and assigns a value to its members, including n:
void init_node(node* n)
{
n->idNode = ...;
n->n = calloc(MAX, sizeof(int));
n->counter = 0;
}
Note: you still need to handle errors (e.g. calloc may fail) in the function and propagate errors to its caller.
You can't have statements or initialize an variable inside a structures.
For fix your problem
typedef struct Node {
int idNode;
int* n; //pointer to the int nodes in the dynamically created array of nodes
int counter;
} node;
int main(void)
{
node data = null;
node.n = calloc(sizeof(int), MAX);
node.idNode = 0;
node.counter = 0;
return (0)
}
Now you have initialize your struct
Starting point
I tried to create a struct that would incude a dynamic array
The problem I see in your initial snippet is you mix definition, declaration and use.
From https://www.geeksforgeeks.org/difference-between-definition-and-declaration:
Declaration of a variable is for informing to the compiler the following information: name of the variable, type of value it holds and the initial value if any it takes. i.e., declaration gives details about the properties of a variable. Whereas, Definition of a variable says where the variable gets stored.
Steps to get a basic knowledge of how to do it.
Firstly, you must know how to create a struct.
The next step is how to typedef it.
The next step is how dynamic arrays are declarated, defined, created, stored, modified or destroyed (the life cycle). Pay attention to erros may occur during the execution. The happy path of create things in C is not the only one, there are plenty of errors out there!
The next step is how to insert them into a typedef'd struct.
And the last step is use that typedef struct with a dynamic array inside it. Even you can create multiple dynamic arrays in the struct!
Note: Steps, 1, 2 and 4 may be ordered in other ways depend on the programmer
There is no shortcuts, no trial and error and, of course, you must create test programs to ensure the stuff you want and the stuff you program are the same thing.
n = calloc(MAX, sizeof(int));
int counter = 0;
You cannot use statements to execute inside of the declaration of a structure. You need to initialize n and counter inside of a function after an object of node has been defined.
E.g.:
typedef struct
{
int idNode;
int* n;
int counter;
}
node;
int main (void)
{
node a;
a.n = calloc(MAX, sizeof(int));
a.counter = 0;
}

Define array in various types outside and inside of main

suppose I have the following code:
#define SIZE 5
### FIRST OPTION ###
int main(int argc , char** argv){
### SECOND OPTION ###
return 0;
}
I have checked online and couldn't really understand what will be the difference between those three code statements (on compile and runtime) when I write them instead of first option line and second option line (each statement will be wrote individually) :
struct my_struct array[SIZE]
static struct my_struct array[SIZE]
struct my_struct** array = (struct my_struct**)malloc(SIZE*sizeof(struct my_struct*))
Michael
Option '1' can be used to define your array in a global scope or in a scope of a function, like main. In the following example 'array' is declared in the global scope and is potentially visible to any other module in at link time (if such a module declares it as 'extern'. There is only one copy of this array in the program.
file1.c
struct my_struct array[SIZE];
int main() {
...
array[0] = ...;
}
this file can access the declaration in file1.c
file2.c
extern struct my_struct array[SIZE];
void foo() {
...
array[1] = array[0];
}
Now, if you declare it inside a function, than a new copy of the array will be allocated (in stack) every time the function is called.
int foo() {
struct my_struct array[SIZE];
....
}
It will be visible inside of the function only. 'main' is a normal function and the rule works there as well.
using static (#2) changes the meaning of allocation. If used outside, there will be only one copy of the data associated with this particular file. It will be visible from inside the file, but not from outside.
static struct my_struct array[SIZE];
int main() {
...
array[0] = ...;
}
if you use it inside the function, than it will be only a single copy of it associated with this function. It will not change between calls to the same function and will keep previous values. It also be visible from inside the function only.
int foo() {
static struct my_struct array[SIZE];
....
array[0].counter++;
}
for #3 all the global/static rules stay the same, but just for the pointer. The pointer contains an address of the memory where you dynamically allocated the array.

Access values of structs from a pointer in a struct

I'm going to try and keep this as brief as possible.
So I have two structs:
typedef struct someStruct named;
struct someStruct {
void *key;
void *value;
};
typedef struct anotherStruct namedToo;
struct anotherStruct {
named **table;
unsigned int size;
};
Okay great, now ingore any possible mistakes above, this is uneditable code.
Now I have two methods:
namedToo *init(float ignoreThis) {
namedToo *temp;
temp = malloc(sizeof(namedToo)); //some memory for the second struct
temp->table = malloc(sizeof(named)*100); //lets say this 100 is for 100 buckets/cells/named elements
return temp;
Method 2:
int insert(namedToo *temp, void* key, void* value) {
temp->table[0]->key = key; //My problem, I need to access the value and key inside named from the pointer inside namedToo. How can I do this?
}
The comment has my problem :
My problem, I need to access the value and key inside named from the pointer inside namedToo. How can I do this? I would need to change and grab value/key on their own from time to time.
The declaration named **table; says table is pointer to a pointer to named, or alternately an array of pointer to named. The latter is you seem to intend.
This allocation:
temp->table = malloc(sizeof(named)*100);
Allocates space for 100 named, but what you need are 100 named *, and each of those must point to a named. Given the definition of named this is likely enough space, however at this point you have an array of uninitialized pointers. Attempting to access them results in undefined behavior, which in this case manifests as a core dump.
You need to allocate space for an array of pointers, then initialize each of those to a single dynamically allocated instance of named. So you should be allocating space like this:
int i;
temp->table = malloc(sizeof(named *)*100);
for (i=0; i<100; i++) {
temp->table[i] = malloc(sizeof(named));
}
Then your insert method should work properly.

Initialize structures without defining members of structure - C

I am trying to decipher someone's code and I see something that I don't understand. I don't see any references on how structures are applied when members aren't defined in the header or in the beginning of code but are defined later on.. Here is an example of what I am trying to figure out. I noted that Data_t *data; in the header is not defined until we enter the funky function and my compiler errors out on this line. I guess my question would be -- is this a valid way to input data into structures?
Much thanks!
#include <stdio.h>
typedef struct config{
int a;
int b;
int c;
Data_t *data;
} config_t;
int funky(config_t *config);
int main( void )
{
printf("In main()\n");
config_t config;
funky(&config);
printf("a = %d\n", config.a); //accessing config's a member
return 0;
}
int funky(config_t *config)
{
printf("In funky()\n");
Data_t *dataa = config->data;
for(i=0;i<5;i++){
dataa[i].mem1=i;
dataa[i].mem2=4+i;
}
//Set values
config->a = 1;
printf("a = %d\n", config->a); //pointer to config's a member
return 0;
}
The definition of Data_t doesn't appear in your code, which is what's causing the compile error.
Also - to your specific question, that code is dereferencing an uninitialized pointer, which causes undefined behaviour. Initialize the data field in the config structure in main, or you're going to be in trouble. This block of code:
Data_t *dataa = config->data;
for(i=0;i<5;i++){
dataa[i].mem1=i;
dataa[i].mem2=4+i;
}
Is the bad stuff - as you can see, it copies the unitialized pointer out and tries to access memory through it.
The code after that:
//Set values
config->a = 1;
Is fine, and a totally reasonable way to initialize a structure.

Resources