Double Dereference in struct C - c

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.

Related

user input in struct in C?

int a;
scanf("%d",a);
typedef struct mylist {
int info[a];
struct mylist *link;
} Node;
this is my very simple struct and variable 'a' that don't work.
The thing which I want my program to do is to read input from the user and insert the digit into the struct (the user can determine the size of the array), however, I don't know how to do it since I get an error:
"variably modified ‘info’ at file scope".
I want to know whether it is possible to do this in a simple way.
When you use scanf into an integer you must pass a pointer. You may want to check the documentation.
scanf("%d", &a);
As far as using a variable to allocate data, you can do it, but you will want to use malloc most likely after defining your structure as a type.
As pointed out by #David Hoelzer
scanf("%d",a);
should be
scanf("%d",&a);
If you are under C99 you can use flexible array members:
typedef struct mylist {
struct mylist *link;
int info[]; /* should be the last member */
} Node;
and then
Node *node = malloc(sizeof *node + (a * sizeof(int)));
You must have pointer to array of correct size or use flexible array. Here is how to use a pointer initializing it to point to storage of proper size.
struct mylist {
int *info; // or int info[] at the end of struct def if C99 is used
int info_size;
struct mylist *link;
};
int main(void)
{
int *array;
struct mylist m;
if (scanf("%d", &m.info_size) != 1)
{
perror("scanf failed");
exit(EXIT_FAILURE);
}
// ok
array = malloc(sizeof(int) * m.info_size);
if (array == NULL)
{
perror("malloc failed");
exit(EXIT_FAILURE);
}
// ok, commit changes
m.info = array;

store an int in a node

#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.

Learning C - Compiling error allocating pointers

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;

A simple stack implementation using C

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));

c programming: need fresh eyes to look at this [demo code != homework]

Essentially I want qPtr[0] to hold sPtr[0]
struct myQueue{
struct sample* node;
int front;
int size;
int numElements;
};
struct sample{
int field1[5];
char field2[10];
}
int main(){
struct myQueue* qPtr = malloc(10 * sizeof(struct myQueue);
struct sample* samplePtr = malloc(10 * sizeof(struct sample); //assume this array has been initialized
enqueue(qPtr, samplePtr[0]); //this does not work
}
//returns 1 if enqueue was successful
int enqueue(struct myQueue* qPtr, struct sample* sPtr){
qPtr->node[(qPtr->front + qPtr->numElements) % qPtr->size] = sPtr; //code pertains to circular array implementation of queues
return 1;
}
I've been at it for about 2 hours now and would appreciate some clarification on what I'm doing wrong conceptually. thank you!
samplePtr[0] gives the object itself, not a pointer to the object. Try sending &samplePtr[0] or samplePtr itself. enque function, second parameter expects a type of struct sample* and not struct sample.
How about:
enqueue(qPtr, &samplePtr[0]);
The second parameter to enqueue() takes a pointer to a struct sample.
Your code has 2 fundamental problems.
you're passing a struct sample object to enqueue() instead of a pointer to a struct sample. this should be caught by the compiler.
you're setting up an array of queue structures instead of having a single queue structure object that manages an array of pointers to the objects that are on the queue. This is a design problem.
Your code should probably look more like:
struct myQueue{
struct sample* node;
int front;
int size;
int numElements;
};
struct sample{
int field1[5];
char field2[10];
}
struct myQueue q = {0};
int enqueue(struct myQueue* qPtr, struct sample* sPtr);
int main(){
// get memory to hold a collection of pointers to struct sample:
q.node = calloc(10, sizeof(struct sample*));
q.size = 10;
// allocate a sample
struct sample* samplePtr = malloc(sizeof(*samplePtr));
// put the sample on the queue
enqueue(qPtr, samplePtr);
}
//returns 1 if enqueue was successful
int enqueue(struct myQueue* qPtr, struct sample* sPtr){
qPtr->node[(qPtr->front + qPtr->numElements) % qPtr->size] = sPtr; //code pertains to circular array implementation of queues
return 1;
}

Resources