#include <stdio.h>
#include <stdlib.h>
struct Fraction {
int num;
int denom;
};
struct PolyTerm {
int expo;
struct Fraction coeff;
};
struct PolyNode {
struct PolyTerm* dataPtr;
struct PolyNode* next;
};
typedef struct Fraction* FractionAddr;
typedef struct PolyNode* PolyNodeAdr;
typedef struct PolyNode* PolyList;
int main() {
int exponet;
PolyNodeAdr polyNode = 0;
printf("\n\tPlease Enter expoent: ");
scanf("%d", &exponet);
polyNode->dataPtr->expo = exponet;
//printf("\n%d\n",polyNode->dataPtr->expo);
return;
}
on the above code, I am trying to store the exponet into the expo in the struct of polynode
but I tried many ways, but errors keep appearing
isn't expo is an int? why I can't store the exponet (int) into it?
I checked a few ways, when I just put struct PolyTerm dataPtr;in the struct of polyNode
and polyNode->dataPtr.expo = exponet; in the main, it would work
I think because the dataPtr is a pointerstruct PolyTerm* dataPtr;
but I have no idea to fix it
can anyone explain to me why I can't do that and what is the solution for it?
You have to allocate memory for all pointers that you gonna dereference. And free the memory after you are done with it.
int main() {
int exponet;
PolyNodeAdr polyNode = (PolyNodeAdr)malloc(sizeof(PolyNode));
polyNode->dataPtr = (PolyTerm*)malloc(sizeof(PolyTerm));
printf("\n\tPlease Enter expoent: ");
scanf("%d", &exponet);
polyNode->dataPtr->expo = exponet;
//printf("\n%d\n",polyNode->dataPtr->expo);
free(polyNode->dataPtr);
free(polyNode);
return 0;
}
No memory was allocated for PolyNodeAdr polyNode
You have to add this after your declaration of polyNode for polyNode->dataPtr->expo = exponet; to work
polyNode = malloc( sizeof( struct PolyNode )) ;
polyNode->dataPtr = malloc( sizeof( struct PolyTerm )) ;
Note the usage of struct PolyNode not PolyNodeAdr since you changed PolyNodeAdr to a pointer with typedef.
Also you shouldn't typedef a pointer, since you lose the information that the name is a pointer.
For example:
typedef struct PolyNode* PolyNodeAdr;
Should be:
typedef struct PolyNode PolyNodeAdr;
So later you declare:
PolyNodeAdr * polyNode;
You are Dereferencing a NULL pointer.
polyNode == NULL
dataPtr == anything.
so polyNode->dataPtr->expo is actually (NULL)->dataPtr->expo. it doesnt have meaning. there is segmentation fault because you are trying to access a restricted memory. thats why windows pops that message.
EDIT:thanks to #Nik for pointing out the errors in my answer.
Related
I am trying to create a union of 2 structs (dfp and affine) and want to allocate them dynamically. I am getting errors in creating particular struct array inside union. Am I declaring union in right way?
#include <stdio.h>
#include <stdlib.h>
struct{
int fp;
}dfp;
struct{
int scale;
int zp;
}affine;
union{
struct dfp *df;
struct affine *af;
}quant;
struct member{
int total;
union quant arr;
};
int main(void) {
// your code goes here
struct member* ptr;
ptr = (struct member *)malloc(sizeof(struct member));
ptr->total = 2;
int type = 0;
if(!type){
ptr->arr->df = (struct dfp*)malloc(ptr->total*sizeof(struct dfp)); //error
for(int i=0;i<2;i++){
ptr->arr->df->fp[i] = 10;
}
}
else{
ptr->arr->af = (struct affine*)malloc(ptr->total*sizeof(struct affine)); //error
for(int i=0;i<2;i++){
ptr->arr->af->scale[i] = 10;
ptr->arr->af->zp[i] = 20;
}
}
return 0;
}
Most issues have already been pointed out by others separately. This is my attempt at writing a complete answer with explanations and advice.
First off, please check your exact compiler warnings and errors. These are your best help in resolving these kind of issues.
The program does not contain a union of structs, but a union of pointers to structs.
The program's definitions are not correct. Taking dfp as an example. This, struct { int fp; } dfp;, defines an anonymous struct with the the variable name dfp. The name of the struct should go before the struct declaration list, e.g. struct dfp { int fp; };. See here or see the C standard specifications.
Judging by the code in main, the member variables of the structs should be arrays of size 2 instead of single ints.
The operator -> is for "member access using a pointer". Since arr is not a pointer, use a dot (.) to access its members. See here.
Dynamically allocated memory must be free'd, or else the program will have one or more memory leaks.
Here is the full code with all mentioned corrections:
#include <stdio.h>
#include <stdlib.h>
struct dfp {
int fp[2];
};
struct affine {
int scale[2];
int zp[2];
};
union quant {
struct dfp *df;
struct affine *af;
};
struct member {
int total;
union quant arr;
};
int main(void) {
struct member* ptr;
ptr = (struct member *)malloc(sizeof(struct member));
ptr->total = 2;
int type = 0;
if(!type) {
ptr->arr.df = (struct dfp*)malloc(ptr->total*sizeof(struct dfp));
for(int i=0;i<2;i++){
ptr->arr.df->fp[i] = 10;
}
}
else {
ptr->arr.af = (struct affine*)malloc(ptr->total*sizeof(struct affine));
for(int i=0;i<2;i++){
ptr->arr.af->scale[i] = 10;
ptr->arr.af->zp[i] = 20;
}
}
if(!type) {
free(ptr->arr.df);
}
else {
free(ptr->arr.af);
}
free(ptr);
}
Correct the struct definition as below:
struct dfp {
int fp;
};
struct affine{
int scale;
int zp;
};
I have these structures in C:
typedef struct Game{
char* name;
char* team_1;
char* team_2;
int score[2];
} *pGame;
typedef struct Team{
char *name;
int victories;
} *pTeam;
typedef struct node_game{
pGame game;
struct node_game *next;
} *link_game;
typedef struct node_team{
pTeam team;
struct link_team *next;
} *link_team;
typedef struct head{
link_game game_list;
link_team team_list;
} *pHead;
And these functions to go with it:
void initialize(pHead* heads,int m){
int i;
heads = (pHead*)malloc(m*sizeof(pHead));
for (i = 0; i < m; i++)
heads[i] = NULL;
}
//this function is to allocate dynamic memory for a string
char* str_dup(char* buffer){
char* str;
str = (char*) malloc(sizeof(char)*(strlen(buffer)+1));
strcpy(str,buffer);
return str;
}
void add_team(pHead* heads, char* name){
char* name_dup;
link_team new_team = (link_team) malloc(sizeof(struct node_team));
name_dup = str_dup(name);
new_team->team->name = name_dup; //this line gives me segmentation fault
}
int main(){
pHead* heads;
initialize(heads,M);
add_team(heads, "manchester");
return 0;
}
Why is it that the last line of add_team gives me segmentation fault? I've looked at this with the VSC debugger and it seems it should go well. My problem is most likely that I'm not allocating memory when I should, but I can't see where. (also, the function will do more stuff, but it gives me segmentation fault already there).
At the time you do this:
new_team->team->name = name_dup;
You allocated memory for new_team, but not for new_team->team. This means that new_team->team->name dereferences an uninitialized pointer invoking undefined behavior.
You need to allocate space for it first:
link_team new_team = malloc(sizeof(struct node_team));
new_team->team = malloc(sizeof(struct Team));
Or you can change team from a struct Team * to a struct Team and access it directly. You probably want to do the same for game in struct node_game.
I have the following code. It seems the reading sequence is wrong. Any help?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct punct{
int x;
int y;
}COORD;
typedef struct nod{
COORD *coord;
struct nod *urm;
}NOD;
int main()
{
NOD *head= malloc( sizeof(NOD) );
scanf("%d", &head->coord->x );
scanf("%d", &head->coord->y );
printf("%d, %d", head->coord->x , head->coord->y);
return 0;
}
I have successfully managed to access only the x field of the struct by using head->coord, and from what I can tell that's the issue with my code. I'm already on the first field of the first struct so I can't access x/y because of that.
You did not initialize the coord variable so you shoud malloc some space for that too.
head->coord = malloc( sizeof (COORD) );
But in this case it might be best to put COORD in NOD instead of referencing to it!
So:
typedef struct nod{
COORD coord;
struct nod *urm;
}NOD;
You should only really make a pointer to it when you are going to swap the object a lot or when its a more complex object.
You haven't initialized head->coord. Dereferencing uninitialized pointers result in undefined behaviour. You need to do something like:
head->coord = malloc( sizeof (COORD) );
You should also check the return value of malloc() for failures.
I'm new to C and trying to compile this simple code, but it's not working and I'm not sure why. Can anyone help me?
int main(int argc, const char * argv[])
{
struct Node{
int value;
struct Node *next;
};
struct Node* x;
struct Node* y;
struct Node* z;
x = malloc(sizeof(Node));
y = malloc(sizeof(Node));
z = malloc(sizeof(Node));
return 0;
}
The compiler is complaining about the use of an undeclared identifier ‘Node’:
x = malloc(sizeof(Node));
y = malloc(sizeof(Node));
z = malloc(sizeof(Node));
Welcome to SO and the wonderful world of C!
A few pointers for you:
Syntax-ically there's no problem with defining a struct inside a function, but typically it's defined outside so that it can be used in other functions. For example:
main(){
struct nodedef{vars};
add_to_node(node var);
}
add_to_node(node var)
{
// How can I add a to a node when I don't know what that is?
}
The main problem with your code is that you aren't correctly referencing your node later on, if I declaire:
struct me {
int i;
};
Then anytime I reference this type of struct, I have to explicitly say struct again:
struct me myself;
myself = malloc(sizeof(struct me));
myself.i = 5;
The way to avoid this reuse of the struct keyword is to use the typedef:
typedef struct me {
int i;
}m;
m myself;
myself = malloc(sizeof(m));
myself.i = 5;
Last point is anytime you allocate some memory via malloc() make sure you call free() to release that memory:
free(myself);
Or else you'll have a memory leak.
Try sizeof(struct Node) instead.
struct Node should be used to refer to the structure. If you want the code above works, an alternative is typedef-ing the struct Node structure as
typedef struct Node {
int value;
struct Node *next;
} Node;
I had written a program in C to implement a simple stack. But I am getting segmentation fault in my program and finding it hard to find out what is wrong. Can any one help,
#include<stdio.h>
#include<stdlib.h>
struct stack_structure{
int stack_array[10];
int stack_pointer;
};
void push_into_stack(struct stack_structure *,int);
int main(){
int no = 8;
struct stack_structure *st;
st->stack_pointer = -1;
push_into_stack(st,no);
return 0;
}
void push_into_stack(struct stack_structure *s,int no){
s -> stack_pointer++;
s -> stack_array[s -> stack_pointer] = no;
}
struct stack_structure *st;
This only creates a pointer to a struct stack_structure. It does not allocate memory for the struct stack_structure itself.
You can try with this:
struct stack_structure st;
st.stack_pointer = -1;
push_into_stack(&st,no);
The other option is to dynamically allocate (and free) that structure:
struct stack_structure *st = malloc(sizeof(struct stack_structure));
...
// when you're done with it
free(st);
See these lines:
struct stack_structure *st;
st->stack_pointer = -1;
You've declared a pointer variable but then you're using it uninitialized. A pointer has to point at something, and this one doesn't have anything to point to. The simplest fix would be to change these lines to:
struct stack_structure st1, *st=&st1;
st->stack_pointer = -1;
You need to malloc some space for the structure:
struct stack_structure *st = malloc(sizeof(struct stack_structure));