search and edit function no copy paste? - c

Hi this code is just an example of what im working on. I've got the solution by copying everything from my search function and dump it into my edit function. Is there any better solution rather than just copy pasting?
struct inventory
{
float a,b,c,d;
char something[MAXSIZE];
};
typedef struct inventory Inventory;
struct will contain some float integer and some characters.
void search(const Inventory inv[], int np); // declare search function
void edit(struct inventory inventoryRegister[],int np);
int main(void)
{
int np=0;
struct inventory inventoryRegister[MAXSIZE];
// calling the functions search and edit
search(inventoryRegister, np);
edit(inventoryRegister, np);
return 0;
}
void search(const Inventory inv[], int np)
{
int i,
float min, max;
printf("Enter min max");
scanf("%f %f", &min, &max);
for (i = 0; i < np; i++)
if (inv[i].a >= low && inv[i].a <= high)
{
print..
}
//repeat for b,c,d and something
}
void edit(struct inventory inventoryRegister[],int np)
{
int a;
print("Enter new a");
scanf("%f", &a);
// Here i can copy and paste my entire search function and do a loop to replace the min & max with my new input a.
But is there any easier way to do it? say i call the search(); and somehow extract the elements between min & max and do a loop replacement with a?
Any suggestion?
}

Disclaimer : Its a kind of a psuedo code
struct MinMaxLocation
{
int minloc;
int maxloc;
};
struct MinMaxLocation getMinMaxLocation(struct inventory inventoryRegister[],float min,float max)
{
// your logic to find min and max locations here
struct MinMaxLocation loc;
loc.minloc = // min element location
loc.maxloc = // max element location
return loc;
}
void search(....)
{
struct MinMaxLocation loc_here_search = getMinMaxLocation(inventoryRegister,min,max);
for (i = loc_search_here.min; i < loc_search_here.max; i++)
{
print ...
}
}
void edit(....)
{
struct MinMaxLocation loc_here_search = getMinMaxLocation(inventoryRegister,min,max);
for (i = loc_search_here.min; i < loc_search_here.max; i++)
{
edit the values here ...
}
}

Related

Unable to find the shortest distance in graph using adjacent matrix in c

I am trying to find the shortest distance between two nodes using adjacent matrix and recursive call, but for some reason it always returns 0, i cant find where things are going wrong.
The function 'shortestDist' is a recursive function which returns the shortest cost. If src node contains a direct path to destination than the cost is directly added to array. but if it doesnt the possible nodes replace the source node and a recursive function is called. for a node to replace a source node it must meet the following requirements : 1- it shouldn't be visited, 2- the distance between this.node and destination should be less than prevsrc and dst, 3- the node should not be the destination itself.
`
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define X 99
int **graph;
int numNodes;
char nodes[10][10];
void createGraph(int);
void printGraph();
void addPath(char[],char[],int);
void deleteGraph();
int shortestDist(int,int);
int visited[10];
int min(int[]);
void main()
{
int i,j;
createGraph(5);
addPath("a","b",3);
addPath("b","c",5);
addPath("a","c",9);
printf ("\n%d\n",shortestDist(0,2));
printGraph();
}
void createGraph(int no){
int i,j;
numNodes=no;
graph = malloc(sizeof(int*)*no);
for(i=0;i<no;i++){
graph[i] = malloc(sizeof(int)*no);
visited[i] = 0;
}
for(i=0;i<no;i++){
printf("Enter %d node: ",i+1);
scanf("%s",&nodes[i]);
for(j=0;j<no;j++){
graph[i][j] = X;
}
}
}
void addPath(char from[],char to[],int dist){
int i,j;
for(i=0;i<numNodes;i++){
for(j=0;j<numNodes;j++){
if(strcmp(from,nodes[i])==0 && strcmp(to,nodes[j])==0){
graph[i][j]=dist;
}
}
}
}
void printGraph(){
int i,j;
for(i=0;i<numNodes;i++){
for(j=0;j<numNodes;j++){
printf("%d ",graph[i][j]);
}
printf("\n");
}
for(i=0;i<numNodes;i++){
printf("%d ",visited[i]);
}
}
void deleteGraph(){
free(graph);
}
int shortestDist(int src,int dst){
int possPaths=0,i;
int count=0;
visited[src] = 1;
for(i=0;i<numNodes;i++){
if(graph[src][i]!=X){
possPaths++;
}
}
int possNodes[possPaths];
for(i=0;i<possPaths;i++){
possNodes[i] = X;
}
if(graph[src][dst]!=X){
possNodes[count] = graph[src][dst];
count++;
}
for(i=0;i<numNodes;i++){
if(graph[src][i]!=X && visited[i]==0 && i!=dst){
printf("?");
possNodes[count] = graph[src][i] + shortestDist(i,dst);
count++;
}
}
for(i=0;i<possPaths;i++){
printf("->%d\n",possNodes[i]);
}
return min(possNodes);
}
int min(int arr[]){
int minimum=arr[0],i;
for(i=0 ; i<numNodes ; i++){
if(arr[i]<minimum){
minimum = arr[i];
}
}
return minimum;
}
`
Output is always returing 0.
The min function processes numNodes array elements, but it is passed the array possNodes with only possPaths elements, hence it fails to return a correct minimum.
I suggest to change it to
int min(int possPaths, int arr[possPaths])
{
int minimum = X;
for (int i = 0; i < possPaths; ++i)
if (arr[i] < minimum) minimum = arr[i];
return minimum;
}
and invoke it so:
return min(possPaths, possNodes);

how to write a reading function of a struct variable?

I have to write a function that reads from the keyboard a structure type variable and a function that displays a structure type variable. Subsequently, I have to use these functions to read and display a n number of elements of the structure. That's what I managed to write, but it does not look very correct and logical. I'd be very happy to help. Here's my code :
#include <stdio.h>
struct data{
int d, m, y;
}dt;
void readData(struct data element){
printf("\nData format dd-mm-yyyy : ");
scanf("%d %d %d", &element.d,&element.m,&element.y);
}
void read(struct data element,int n){
for(int i = 0; i < n; i++){
readData(element);
}
}
void display(struct data element){
printf("\n %d.%d.%d\n",element.d,element.m,element.y);
}
void displayN(struct data element, int n){
for(int i = 0; i < n; i++){
display(element);
}
}
int main() {
struct data dd1;
read(dd1,3);
displayN(dd1,3);
return 0;
}
It looks like you want to use an array.
#include <stdio.h>
struct data{
int d, m, y;
}dt;
/* use pointer to an element to modify the data */
void readData(struct data *element){
printf("\nData format dd-mm-yyyy : ");
scanf("%d %d %d", &element->d,&element->m,&element->y);
}
/* use an array to read data (just syntax sugar, this argument element is actually a pointer) */
void read(struct data element[],int n){
for(int i = 0; i < n; i++){
readData(&element[i]);
}
}
/* you don't need to use a pointer here because the value is just printed and not changed */
void display(struct data element){
printf("\n %d.%d.%d\n",element.d,element.m,element.y);
}
/* use an array to print multiple data */
void displayN(struct data element[], int n){
for(int i = 0; i < n; i++){
display(element[i]);
}
}
/* define the number of elements and use that to avoid typo */
#define N 3
int main(void) {
struct data dd1[N]; /* declare an array */
read(dd1,N);
displayN(dd1,N);
return 0;
}

can't return the right variable in C [duplicate]

This question already has answers here:
How do I return multiple values from a function in C?
(8 answers)
Closed 3 years ago.
I want to try write Kadane algorithms using C. Instead of just return maximum subarray value, I also want to return the start and end index.
And here's the code :
#include <limits.h>
#include <stdio.h>
int kadane(int A[], int size){
int current_max = INT_MIN;
int global_max = INT_MIN;
int start, last;
for (int i = 0; i <= size; i++){
if (A[i] > A[i] + current_max){
current_max = A[i];
start = i;
} else {
current_max += A[i];
};
if (current_max >= global_max){
global_max = current_max;
last = i;
};
};
return (start, last ,global_max);
}
int main(){
int sum, size, start, last;
int A[] = {3,-4,5,1,9,-10,11,2,5,-1,2};
size = sizeof(A)/sizeof(A[0]);
start, last, sum = kadane(A, size-1);
printf("start at %d ; end at %d; sum : %d\n", start, last, sum);
return 0;
}
Although the answer of maximum sum is right, the value of start and last are really weird. I use printf to check the value of start and last in the for loop of kadane function, and it seems work fine there. So I thought the problem might have something to do with the way I return variable.
so I modify some part of code like this :
int kadane(int A[], int size){
......
......
return (&start, &last ,global_max);
}
and then using pointer to store them :
int main(){
.......
.......
int *start;
int *last;
*start, *last, sum = kadane(A, size-1);
printf("start at %d ; end at %d; sum : %d\n", *start, *last, sum);
return 0;
}
then I got "Segmentation Fault 11" error.
I try to understand and search what I'm doing wrong here but I just can't find it.The only solution that work is to store variable start and last in global so that I can just call then anywhere without return.But I feel like that is not a suitable solution. Can anyone help me here?
You have two solutions:
1: Return a struct which contains all the types you need.
struct data {
int start;
int last;
int global_max;
};
struct data kadane(int A[], int size){
stuct data test = { 1, 1, 1 };
......
......
return test;
}
void main() {
......
struct data t = kadane(A, ize);
}
2: Use pointers to pass out values.
void kadane(int A[], int size, int *start, int *last, int *global_max) {
......
......
*start = 1;
*last= 1;
*global_max= 1;
}
void main() {
......
int a, b, c;
kadane(A, size, &a, &b, &c);
}
From
How do I return multiple values from a function in C?

C: Value of variable changing without re-assignment

I am implementing Kruskal's algorithm.
After I call graph() in the following code, the value of nodes change. I'm not quite sure why -- if anyone could clear this up I would greatly appreciate it. I'm not accessing the value of nodes from within graph, and both nodes & edges, the array being accessed, are allocated outside of the stack!
struct node {
int parent, rank;
};
typedef struct node node;
struct edge {
int fromvertex, tovertex;
float weight;
};
typedef struct edge edge;
node* nodes;
edge* edges;
typedef enum {Unvisited, Visited} vertexstate;
int main (int argc, char const *argv[])
{
void getcount(int*, int*);
void graph(int, int);
void makeset(int);
int hasspantree(int, int, int);
void kruskal(int, int);
int printmcst(int);
int nodecount, edgecount, i, totalcost=0;
getcount(&nodecount, &edgecount);
for (i = 1; i <= nodecount; i++)
makeset(i);
printf("%d \t %d\n", nodes[6].parent, nodes[6].rank );
graph(nodecount, edgecount);
printf("%d \t %d\n", nodes[6].parent, nodes[6].rank );
printf("Has a spanning tree?");
if(hasspantree(1, nodecount, edgecount)) {
printf("\t Yes.\n");
kruskal(nodecount, edgecount);
printf("MCST found:\n\n");
totalcost = printmcst(nodecount);
printf("\nCost: %d", totalcost);
}
else {
printf("No.");
exit(0);
}
return 0;
}
void graph(int nodecount, int edgecount)
{
for (int i = 0; i < edgecount; i++) {
scanf("%d", &edges[i].fromvertex);
scanf("%d", &edges[i].tovertex);
scanf("%f", &edges[i].weight);
}
}
void getcount(int *nodecount, int *edgecount)
{
scanf("%d", nodecount);
scanf("%d", edgecount);
nodes = malloc(*nodecount * sizeof(node));
edges = malloc(*edgecount * sizeof(edge));
}
void makeset(int x)
{
nodes[x].parent = x;
nodes[x].rank = 0;
}
one obvious error is accessing the nodes array starting at index 1 instead of 0 and this would cause buffer overrun when you access the last element
for (i = 1; i <= nodecount; i++) <-- here i should start at 0 and access only up to nodecount-1
makeset(i);

How to sort Struct using qsort in C programming

I have created an array of struct and i would like to sort them using qsort to sort dates chronologically to the string month or i should say char month[]. how can i make the following code display the struct according to a month. please advice. thanks
struct dates
{
int index;
int day;
int year;
char month[15];
};
int i=0;
int count = 0 ;
char test ='\0';
int total =0;
printf("Please enter the number of dates you need to display");
scanf("%d",&total);
struct dates *ip[total];
for(count =0; count< total; count++){
ip[count] = (struct dates*)malloc(sizeof(struct dates));
printf("\nEnter the name month.");
scanf("%s", ip[count]->month);
printf("\nEnter the Day.");
scanf("%d",&ip[count]->day);
printf("\nEnter the Year.");
scanf("%d", &ip[count]->year);
}
for(i=0; i<total; i++){
printf("%s %d %d\n\n",ip[i]->month,ip[i]->day,ip[i]->year);
}
you can define your own comparator to sort http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/
So to sort integers you would use
int intcomp(void *a, void *b){
int *_a = (int *)a;
int *_b = (int *)b;
if(*_a > *_b) return -1;
if(*_a == *_b) return 0;
return 1;
}
I think you can make your own comparator function from that.
There's an example in the man page of qsort
static int
cmp(const void *p1, const void *p2)
{
int y1 = ((const struct dates*)p1)->year;
int y2 = ((const struct dates*)p2)->year;
if (y1 < y2)
return -1;
else if (y1 > y2)
return 1;
/* years must be equal, check months */
...
}
and then
qsort(dates, total, sizeof(*dates), cmp);

Resources