Issues with pointers and realloc, with program crashed errors in C - c

In main.c
#include <stdio.h>
#include "poly.h"
int main (void)
{
struct poly *p0 = polySetCoefficient (polySetCoefficient (polySetCoefficient (polyCreate() , 0, 4.0), 1, -1.0), 10, 2.0);
//polyPrint (p0);
return 0;
}
In poly.c I've just included two functions that I am dealing with, it seems as though polySetCoefficient is the one that's giving me problems. I've commented out the printf statements, but I used those to determine where exactly the program crashes. Apparently, it actually goes through the whole function before it crashes, so I am not exactly sure where the error is coming from. Secondly, in my main.c file I am only calling two functions. Another issue is that everytime I go through polySetCoefficient, my previous entries are replaced with 0s. I think that could be because of the way I set elements in the array to 0, but I carefully made sure to set elements to 0 from the previous size of the array to the new size of the array, excluding the last index.
struct poly *polyCreate()
{
struct poly *q;
q = malloc(sizeof(struct poly));
q->c = malloc(sizeof(double));
q->c[0] = 0.0;
q->size = 0;
//printf("polyCreate: %g\n", q->c[0]);
return q;
}
struct poly *polySetCoefficient(struct poly *p, int i, double value)
{
//printf("%d\n", i*sizeof(double));
if (p->size < i)
{
printf("Old: %d, New: %d\n", sizeof(p->c)/sizeof(double), i);
p->c = realloc(p->c, i+1*sizeof(double));
printf("New: %d \n", sizeof(p->c));
for(int l = p->size; l <= i; l++ )
{
if(l != i)
{
p->c[l] = 0;
printf("set to 0\n");
}
else
{
p->c[l] = value;
printf("F:set to %g\n", p->c[i]);
}
}
printf("Did we come here?\n");
p->size = i;
} else {
p->c[i] = value;
}
printf("The %d'th coefficient is %g\n", i, p->c[i]);
printf("Cof 0: %g, Cof 1: %g, Cof 10: %g", p->c[0], p->c[1], p->c[10]);
return p;
}
In poly.h
struct poly
{
double *c;
int size, length;
};
struct poly *polyCreate();
struct poly *polyDelete(struct poly *p);
struct poly *polySetCoefficient (struct poly *p, int i, double value);
double polyGetCoefficient (struct poly *p, int i);
int polyDegree (struct poly *p);
void polyPrint (struct poly *p);
struct poly *polyCopy (struct poly *p);
struct poly *polyAdd (struct poly *p0, struct poly *p1);
struct poly *polyMultiply (struct poly *p0, struct poly *p1);
struct poly *polyPrime (struct poly *p);
double polyEval (struct poly *p, double x);

This version of the code compiles cleanly and runs plausibly (but not really correctly) without crashing.
One key change is the one identified by immibis in his answer, the corrected size calculation.
The other key change is not printing coefficient 10 when there is no coefficient 10 yet. If you attempt to print that sooner, then you invoke undefined behaviour; anything may happen.
I fixed some printf() formats; on a 64-bit machine, you need to use %zu (or %zd at a pinch) to print a size_t. I removed the unused length member of the structure. I really don't know how to format your single-line multi-call statement neatly. I don't mind slightly longer than 80 character lines, but I don't normally go as far as 120. I definitely prefer the p1 version, not least because it would be possible to error check as you go. At the moment, I've used assert(ptr != 0); where there should be an allocation error check.
Output:
The 0'th coefficient is 4
The 1'th coefficient is -1
Old: 1, New: 10
New: 8
p[1] set to 0
p[2] set to 0
p[3] set to 0
p[4] set to 0
p[5] set to 0
p[6] set to 0
p[7] set to 0
p[8] set to 0
p[9] set to 0
p[10] set to 2
Did we come here?
The 10'th coefficient is 2
Cof 0: 4, Cof 1: 0, Cof 10: 2
Note that you've clobbered the first coefficient with zero when you extended to 10.
Code:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
struct poly
{
double *c;
int size;
};
struct poly *polyCreate(void);
struct poly *polySetCoefficient(struct poly *p, int i, double value);
int main(void)
{
/* I don't know how to format this neatly! */
struct poly *p0 = polySetCoefficient(
polySetCoefficient(
polySetCoefficient(polyCreate(), 0, 4.0),
1, -1.0),
10, 2.0);
assert(p0 != 0);
/*
struct poly *p1 = polyCreate();
p1 = polySetCoefficient(p1, 0, 4.0),
p1 = polySetCoefficient(p1, 1, -1.0);
p1 = polySetCoefficient(p1, 10, 2.0);
*/
return 0;
}
struct poly *polyCreate(void)
{
struct poly *q = malloc(sizeof(struct poly));
assert(q != 0);
q->c = malloc(sizeof(double));
assert(q->c != 0);
q->c[0] = 0.0;
q->size = 1;
return q;
}
struct poly *polySetCoefficient(struct poly *p, int i, double value)
{
assert(p != 0);
if (p->size < i)
{
printf("Old: %zu, New: %d\n", sizeof(p->c)/sizeof(double), i);
p->c = realloc(p->c, (i+1)*sizeof(double));
assert(p->c != 0);
printf("New: %zu\n", sizeof(p->c));
for (int l = p->size; l <= i; l++)
{
if (l != i)
{
p->c[l] = 0;
printf("p[%d] set to 0\n", l);
}
else
{
p->c[l] = value;
printf("p[%d] set to %g\n", i, p->c[i]);
}
}
printf("Did we come here?\n");
p->size = i;
}
else
{
p->c[i] = value;
}
printf("The %d'th coefficient is %g\n", i, p->c[i]);
if (i >= 10)
printf("Cof 0: %g, Cof 1: %g, Cof 10: %g", p->c[0], p->c[1], p->c[10]);
return p;
}

The missing brackets here could be the problem:
p->c = realloc(p->c, i+1*sizeof(double));
Change it to:
p->c = realloc(p->c, (i+1)*sizeof(double));

Related

How to access a double pointer to an array in a structure with a pointer to the structure

Header file:
#include <stdbool.h>
#ifndef PARRAY_H
#define PARRAY_H
typedef struct patype *parray;
parray newParray(int lower,
int upper); // returns a parray indexed with
// values in {lower,...,upper} where
// lower < upper; if lower is not less
// than upper print the warning message
// "Warning - illegal bounds for array\n"
// and return NULL
void freeParray(parray); // frees up all of parray as needed
bool put(parray p, int i, void *item); // equivalent to p[i] = item; does
// bounds checking and does nothing
// returning false if index is out
// of bounds, returns true if successful
void *get(parray p,
int i); // returns p[i] if index is in bounds of array;
// operation is undefined if index is out of bounds.
// Print "Warning - illegal index\n" if index is out of
// bounds.
int lb(parray); // returns lower bound of array
int ub(parray); // returns upper bound of array
int size(parray); // returns size of array
C file:
// Implimentation
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
// void *vptr
typedef struct patype *parray;
typedef struct patype {
int count;
int upper;
int lower;
void **arr;
} patype;
parray newParray(int lower, int upper) // creates the parray
{
if (lower > upper) {
printf("Warning - illegal bounds for array\n");
return NULL;
}
void *data = malloc(sizeof(struct patype));
((patype *)data)->upper = upper;
((patype *)data)->lower = lower;
((patype *)data)->count = upper - lower;
((patype *)data)->arr = malloc(sizeof(void *) * upper + lower);
return data;
}
int lb(parray p) // returns lower bound
{
return p->lower;
}
int ub(parray p) // returns upper bound
{
return p->upper;
}
int size(parray p) // returns size
{
return p->count;
}
bool put(parray p, int i, void *item) // need to see if array at i is = to item
{
for (k = 0; k < p->count; k++) {
printf("%d\n", *(int *)p);
if (p == item) return true;
}
return false;
}
// void *get(parray p, int i) //Need to return the actual array value if its in
// bounds but not working
// {
// p[i] = i;
// return p[i];
// }
void freeParray(parray p) // frees memory
{
free(p);
}
#include <stdio.h>
#include <stdlib.h>
#include "parray.h"
// Driver Code
int main(void) {
parray pa;
pa = newParray(5, 20);
int *p1 = malloc(sizeof(int));
float *p2 = malloc(sizeof(float));
char p3[20];
put(pa, 5, p1);
put(pa, 6, p2);
put(pa, 7, p3);
// get(pa,5);
ub(pa);
size(pa);
lb(pa);
printf("Lower Bounds %d\n", lb(pa));
printf("Upper Bounds %d\n", ub(pa));
// printf("%d",size(pa));
printf("Check puts %d\n", put(pa, 7, p1));
printf("Check puts %d\n", put(pa, 6, p2));
printf("Check puts %d\n", put(pa, 7, p3));
// printf("%d get\n",*(int*)get(pa,5));
freeParray(pa);
printf("(program compiled & ran)\n");
}
Need to access the arr in put and get but I have no idea how to.
I've tried the usual p->arr but I can't seem to get anything to work. But I just need to make functions put and get I've posted the driver code parray.h and the implementation file.
The project is basically just an array of void pointers but I don't know why its giving me such a rough time thank you sorry for the mistake earlier learning.

adding two polynomials using dynamic arrays

I have the following code written. After i run the code it works fine until it tries to excecute the function add2Poly. Thereafter i get a segementation fault. I am new to programming so i cant understand what is causing it.
#include <stdio.h>
#include <stdlib.h>
struct poly{
double power[5];
double* coeff;
};
struct poly add2Poly(struct poly add1, struct poly add2)
{
struct poly p3;
p3.coeff = malloc(5 * sizeof * p3.coeff);
printf("We will add the two polynomials and put the result in a third polynomial p3.");
int size1 = sizeof(add1.coeff);
int size2 = sizeof(add2.coeff);
for(int i = 0; i < size1; i++)
{
int power = add1.power[i];
for(int j= 0; j < size2; j++)
{
if( power == add2.power[j])
{
p3.coeff[i] = add1.power[i] + add2.power[j];
p3.power[i] = add2.power[j];
}
}
}
return p3;
}
int main(){
struct poly p1;
p1.coeff = malloc(5 * sizeof * p1.coeff);
double a;
printf("Please enter a double value for poly1 coeff:");
scanf("%lf", &a);
double b;
printf("Please enter a double value for poly1 coeff:");
scanf("%lf", &b);
p1.coeff[1] = a;
p1.coeff[2] = b;
printf("Power of poly1: ");
scanf("%lf", &p1.power[1]);
printf("Power poly2: ");
scanf("%lf", &p1.power[2]);
printf("p1: %.1fx^%.1f", p1.coeff[1], p1.power[1]);
printf("+ %.1fx^%.1f\n", p1.coeff[2], p1.power[2]);
struct poly p2;
p2.coeff = malloc(5 * sizeof * p2.coeff);
double c;
printf("Please enter a double value for poly2 coeff:");
scanf("%lf", &c);
double d;
printf("Please enter a double value for poly2 coeff:");
scanf("%lf", &d);
p2.coeff[1] = c;
p2.coeff[2] = d;
printf("Power of poly1: ");
scanf("%lf", &p2.power[1]);
printf("Power poly2: ");
scanf("%lf", &p2.power[2]);
printf("p2: %.1fx^%.1f", p2.coeff[1], p2.power[1]);
printf("+ %.1fx^%.1f\n", p2.coeff[2], p2.power[2]);
struct poly p3;
p3.coeff = malloc(5 * sizeof * p3.coeff);
p3 = add2Poly(p1,p2);
printf("p3: %.1fx^%.1f", p3.coeff[1], p3.power[1]);
printf("+ %.1fx^%.1f\n", p3.coeff[2], p3.power[2]);
}
to be precise it gives me the following error:
segmentation fault(core dumped). I assume it has something to do with the p3 struct but i am not sure.
You want to initialize power by add1.power[i](line 18) when you have not assigned a value of add1.power[i], because at the first iteration i = 0
Then you have not assigned a value of add1.power[0], but only add1.power[1] and add1.power[2] (add1 = p1) and you want use it,
which means that conditional jump depends on uninitialised value : if( power == add2.power[j]) line 22, power is NULL also add2.power[j]
Delete lines 14 and 15 it does not serve you because
sizeof(add1.coeff) return the size in bytes of a pointer to double on your system : the result = 8 here.
You'll have an invalid read, your array poly.power and poly.coeff have a size of 5 while you want to read up to 8 values.
that's why you have this error segmentation fault(core dumped), Because you want to access a memory location that was not allocated to it.
Starting with your idea, if you want your code to work change the loop interval to 1 and 3: because only poly.power[1], poly.power[2], poly.coeff[1] and poly.power[2] are initialized.
Also in line 24 & 25 Do the sum of coefficients and not the sum of power to get the coefficients of the 3rd polynomial.
The way you define the structure of your polynomial can be changed, knowing only the degree of the polynomial. You can avoid the nested loop in your add2Poly function too.
I hope that will heplp you !
Look at the following code:
struct poly add2Poly(struct poly add1, struct poly add2)
{
struct poly p3;
p3.coeff = malloc(5 * sizeof *p3.coeff);
printf("We will add the two polynomials and put the result in a third polynomial p3.\n");
int size1 = sizeof(add1.coeff);// to delate
int size2 = sizeof(add2.coeff);// to delate
for (int i = 1; i < 3; i++)
{
int power = add1.power[i];
for (int j = 1; j < 3; j++)
{
if (power == add2.power[j])
{
p3.coeff[i] = add1.coeff[i] + add2.coeff[i];// do the sum of coefficients and not the sum of power
p3.power[i] = add2.power[i];
}
}
}
return p3;
}
here is an optimized proposal of your problem
#include <stdio.h>
#include <stdlib.h>
struct poly
{
int degree;
double *coeff; // the number of coefficient is equal to degree +1
};
struct poly add2Poly(struct poly p1, struct poly p2)
{
struct poly p3;
struct poly p_min_degree;
if (p1.degree > p2.degree)
{// the degree of the polynomial p3 is the one which has the greatest degree between p1 and p2
p3 = p1;
p_min_degree = p2;
}
else
{
p3 = p2;
p_min_degree = p1;
}
for (int i = 0; i <= p_min_degree.degree; i++)
{
p3.coeff[i] += p_min_degree.coeff[i];
}
return p3;
}
struct poly create_poly()
{// Ask the user to enter the degree of the polynomial and (degree +1) coefficients
struct poly p;
printf("Power of the polynomial : ");
scanf("%d", &p.degree);
p.coeff = malloc((p.degree + 1) * sizeof *p.coeff);
for (int i = 0; i <= p.degree; i++)
{// Read a double as coeff
printf("Enter the coeff x^%d : ", i);
scanf("%lf", &p.coeff[i]);
}
return p;
}
void display_poly(struct poly p)
{// Displays a polynomial p passed as a parameter
//Display example: p degree 2
//p = + 3.00x^2 + 4.00x^1 + 2.00x^0
printf(" p = ");
for (int i = p.degree; i >= 0; i--)
{
printf("+ %.2lfx^%d ", p.coeff[i], i);
}
printf("\n");
}
int main()
{
struct poly p1 = create_poly();
display_poly(p1);
struct poly p2 = create_poly();
display_poly(p2);
struct poly p3 = add2Poly(p1, p2);
printf("The sum of p1+p2 is :");
display_poly(p3);
}

Returning a struct by value gives the same wrong answer every time

I'm trying to return a struct by value to find the position of a node in a tree. However using a wrapper to simplify the function call returns the incorrect value.
Relevant code:
typedef struct {
uint16_t x;
uint16_t y;
} coordinate_t;
coordinate_t node_pos_(uint16_t x, uint16_t y, node_t *node, node_t *find) {
printf("%u, %u\n", x, y);
if (node == find) {
printf("found node at %u, %u\n", x, y);
coordinate_t coords;
coords.x = x;
coords.y = y;
return coords;
}
for (uint16_t i = 0; i < node->child_count; i++) {
node_pos_(x + i, y + 1, node->children[i], find);
}
}
coordinate_t node_pos(node_t *root, node_t *node) {
return node_pos_(0, 0, root, node);
}
int main() {
coordinate_t coords = node_pos(root, child2);
printf("coordinates of %s: %u, %u\n", child2->name, coords.x, coords.y);
return 0;
}
The output:
0, 0
0, 1
0, 2
1, 2
1, 1
found node at 1, 1
coordinates of child2: 2, 0
Currently, your node_pos_ function does not return a value in all execution paths, and has no way to indicate to the caller whether the node was found or not. Both of those are essential for a recursive algorithm that searches for a node in a tree.
In keeping with the spirit of returning a coordinate_t by value, I have reserved the coordinate pair (UINT16_MAX, UINT16_MAX) to represent the "not found" condition.
The modified function is below:
coordinate_t node_pos_(uint16_t x, uint16_t y, node_t *node, node_t *find) {
coordinate_t coords;
printf("%u, %u\n", x, y);
if (node == find) {
printf("found node at %u, %u\n", x, y);
coords.x = x;
coords.y = y;
return coords;
}
// look for node in children
for (uint16_t i = 0; i < node->child_count; i++) {
coords = node_pos_(x + i, y + 1, node->children[i], find);
if (!(coords.x == UINT16_MAX && coords.y == UINT16_MAX)) {
// found
return coords;
}
}
// not found
coords.x = UINT16_MAX;
coords.y = UINT16_MAX;
return coords;
}
As pointed out by #yano, the use of the %u printf format specifier to print a uint16_t value is not portable. A simple fix is to cast the values to unsigned int as below:
printf("found node at %u, %u\n", (unsigned)x, (unsigned)y);
The "proper" way to fix it, avoiding the type cast, is to use the printf format specifier macros from #include <inttypes.h> as below:
printf("found node at %" PRIu16 " , %" PRIu16 "\n", x, y);

Storing data into a dynamic array with structs in C

I am having issues storing data from a file into my dynamic array. I am aware that what I have now is incorrect but it is just there for the moment. I have a file which on the first line contains the amount of lines of data essentially. The following lines have two integers side by side to represent an ordered pair. I want to store those two integers into a struct, point, that symbolizes an ordered pair. Also, the there is an array with such a struct that is inside of another struct, list , which contains the size of the array, or the amount of data currently stored in the array and a capacity which is the total amount of space in the array.
I want to store the two integers into variables of type int and then store them into a point inside of my array that is in my list struct.
I am getting very confused having two structs and am unsure if this is the correct approach. Any feedback would be welcomed.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
typedef struct
{
int x;
int y;
} point;
typedef struct
{
int size;
int capacity;
point *A;
} list;
// Compute the polar angle in radians formed
// by the line segment that runs from p0 to p
double polarAngle(point p, point p0)
{
return atan2(p.y - p0.y, p.x - p0.x);
}
// Determine the turn direction around the corner
// formed by the points a, b, and c. Return a
// positive number for a left turn and negative
// for a right turn.
double direction(point a, point b, point c)
{
return (b.x - a.x)*(c.y - a.y) - (c.x - a.x)*(b.y - a.y);
}
int whereSmallest(point A[], int begin, int end, point p0)
{
point min = A[begin];
int where = begin;
int n;
for (n = begin + 1; n < end; n++)
if (polarAngle(A[n], p0) < polarAngle(min, p0))
{
min = A[n];
where = n;
}
return where;
}
void selectionSort(point A[], int N, point p0)
{
int n, s;
point temp;
for (n = 0; n < N; n++)
{
s = whereSmallest(A, n, N, p0);
temp = A[n];
A[n] = A[s];
A[s] = temp;
}
}
// Remove the last item from the list
void popBack(list *p)
{
int x;
x = p->size - 1;
p->A[x] = p->A[x + 1];
}
// Return the last item from the list
point getLast(list *p)
{
point value;
value = p->A[p->size];
return value;
}
// Return the next to the last item
point getNextToLast(list *p)
{
point value;
value = p->A[p->size - 1];
return value;
}
int main(int argc, const char *argv[])
{
point p0, P;
FILE *input;
list *p;
int N, n, x, y;
/*Assuming that the first piece of data in the array indicates the amount of numbers in the array then we record this number as a reference.*/
N = 0;
input = fopen("points.txt", "r");
fscanf(input, "%d", &N);
/*Now that we have an exact size requirement for our array we can use that information to create a dynamic array.*/
p = (point*)malloc(N*sizeof(point));
if (p == NULL)//As a safety precaution we want to terminate the program in case the dynamic array could not be successfully created.
return -1;
/*Now we want to collect all of the data from our file and store it in our array.*/
for (n = 0; n < N; n++)
{
fscanf(input, "%d %d", &P.x, &P.y);
p->A[n] = P.x;
p->A[n] = P.y;
}
fclose(input);
free(p);
return 0;
}
First of all, your code cannot be compiled because this
p->A[n] = P.x;
p->A[n] = P.y;
is wrong, it should be
p->A[n].x = P.x;
p->A[n].y = P.y;
because A has type point and you should access the members of the struct in order to assign values to them.
But this is just the begining of the problems, you didn't allocate space for the A pointer, so this will not work.
You need to allocate space for an instance of type list, which is done this way
p = malloc(sizeof(*p));
Then you need to initialize p's members, for which
p->values = malloc(N * sizeof(point));
p->capacity = N;
p->size = 0;
as you see space was allocated for the values member.
Check fscanf() to insure data integrity and avoid undefined behavior, if fscanf() fails you would never know with your code and you potentially access uninitialized variables which leads to Undefined Behavior.
Capture the values scanned from the file in two int variables and copy them to the array only if the where sucessfuly read
for (n = 0 ; ((n < N) && (fscanf(input, "%d%d", &x, &y) == 2)) ; n++)
/* check that the values were read from the file _______^ */
{
/* store them in the array */
p->values[n].x = x;
p->values[n].y = y;
p->size += 1;
}
Check that the file did open.
I suggest the following code
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
typedef struct
{
int x;
int y;
} point;
typedef struct
{
int size;
int capacity;
point *values;
} list;
// Compute the polar angle in radians formed
// by the line segment that runs from p0 to p
double polarAngle(point p, point p0)
{
return atan2(p.y - p0.y, p.x - p0.x);
}
// Determine the turn direction around the corner
// formed by the points a, b, and c. Return a
// positive number for a left turn and negative
// for a right turn.
double direction(point a, point b, point c)
{
return (b.x - a.x)*(c.y - a.y) - (c.x - a.x)*(b.y - a.y);
}
int whereSmallest(point values[], int begin, int end, point p0)
{
point min = values[begin];
int where = begin;
int n;
for (n = begin + 1; n < end; n++)
if (polarAngle(values[n], p0) < polarAngle(min, p0))
{
min = values[n];
where = n;
}
return where;
}
void selectionSort(point values[], int N, point p0)
{
int n, s;
point temp;
for (n = 0; n < N; n++)
{
s = whereSmallest(values, n, N, p0);
temp = values[n];
values[n] = values[s];
values[s] = temp;
}
}
// Remove the last item from the list
void popBack(list *p)
{
int x;
x = p->size - 1;
p->values[x] = p->values[x + 1];
}
// Return the last item from the list
point getLast(list *p)
{
point value;
value = p->values[p->size];
return value;
}
// Return the next to the last item
point getNextToLast(list *p)
{
point value;
value = p->values[p->size - 1];
return value;
}
int main(int argc, const char *argv[])
{
FILE *input;
list *p;
int N, n, x, y;
/*Assuming that the first piece of data in the array indicates the amount of numbers in the array then we record this number as a reference.*/
N = 0;
input = fopen("points.txt", "r");
if (input == NULL)
return -1;
if (fscanf(input, "%d", &N) != 1)
{
fclose(input);
return -1;
}
p = malloc(sizeof(*p));
if (p == NULL)
return -1;
/*Now that we have an exact size requirement for our array we can use that information to create a dynamic array.*/
p->values = malloc(N * sizeof(point));
p->capacity = N;
p->size = 0;
if (p->values == NULL)//As a safety precaution we want to terminate the program in case the dynamic array could not be successfully created.
{
free(p);
fclose(input);
return -1;
}
/*Now we want to collect all of the data from our file and store it in our array.*/
for (n = 0 ; ((n < N) && (fscanf(input, "%d%d", &x, &y) == 2)) ; n++)
{
p->values[n].x = x;
p->values[n].y = y;
p->size += 1;
}
fclose(input);
free(p->values);
free(p);
return 0;
}
As you can see there is another improvement you can do to the code, it's not too important but it would avoid using the N and n variables which are not necessary.
Note: before using a function, try to read throughly it's documentation, that will prevent all sorts of unexpected results, for example fscanf(), will help you understand my fixes more.
The variable p should be list p.
The points array allocation is p.A = (point*)malloc(N*sizeof(point));
In the filling loop, since A[n] is a point you can't assign it the int P.x or P.y. You can directly put values into the A[n] point like that:
for (n = 0; n < N; n++)
{
fscanf(input, "%d %d", &(p.A[n].x), &(p.A[N].y));
}
The size and capacity of the list should be initialized: p.capacity = N; right after succesfull memory allocation and p.capacity = n; after filling the array
And in the end you should call free(p.A) instead of free(p).

Adding nodes into a pointer and creating a list which you then use to print polynomials

I'm trying to make a program which prints polynomials in this format, 2x^7 + 1x^2 + 6x^8. I'm using stdarg.h to pass arguments into individual nodes which then pass it into a struct pointer. Eventually Im to use a print function that will print out the nodes in the struct pointer they originally went to. Note the poly create function the first number is the number of terms thatll be in the polynomial and then it prints the polynomials back to front which means when i print it i should expect 1x^7 + 7x^5 + 3x^2 + 3x^4. However when i try to print it out im able to print the first node since it passed but when i attempted to use a for loop to print the rest it gave me an error. I hope my explantion wasnt too bad I tried my best but please ask if i need to clarify something.
code for .h
typedef struct nodeT{
int coef;
int powr;
struct nodeT *next;
} node;
typedef struct {
int num_terms;
node *terms;
} poly;
void poly_print(poly *P) ; //
poly *poly_create(int num,...) ;
This is my code in my .c file
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "poly_ADT.h"
int main(){
poly *P0;
P0 = poly_create(4,3,4,3,2,7,5,1,7);
printf("P0: ");
poly_print(P0);
}
poly *poly_create(int num, ...){
va_list arguments;
va_start(arguments, num);
poly *p = malloc(sizeof(poly));
p->num_terms = num;
int i;
for(i = 0; i < num; i++){
node *temp = (node* )malloc(sizeof(node* ));
temp->coef = va_arg(arguments, int);
temp->powr = va_arg(arguments, int);
p->terms = temp;
}
va_end(arguments);
return p;
}
void poly_print(poly *P) {
int x = 0;
node *n = P->terms;
//printf("%i terms: ", P->num_terms);
int i;
printf("%ix^%i", n->coef, n->powr);
if (n->next) printf(" + ");
printf("\n");
}
poly *poly_create(int num, ...){
va_list arguments;
va_start(arguments, num);
poly *p = malloc(sizeof(poly));
p->num_terms = num;
p->terms = NULL;//! add
int i;
for(i = 0; i < num; i++){
node *temp = (node* )malloc(sizeof(node* ));
temp->coef = va_arg(arguments, int);
temp->powr = va_arg(arguments, int);
temp->next = p->terms;//! add
p->terms = temp;
}
va_end(arguments);
return p;
}
void poly_print(poly *P) {
int x = 0;
node *n = P->terms;
int i;
while(n){
printf("%ix^%i", n->coef, n->powr);
if (n = n->next) printf(" + ");
}
printf("\n");
}

Resources