Okay, so we're supposed to prompt a user to enter 25000 lines of text.
Each line contains three integers each. We are then to pass the third integer in that line to another struct, and connect each integer until you have 25000 interconnected integers.
Here's what I've tried:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct graph{
int begin;
int end;
int cost;
} PathEdge;
int comp_fcn(const void *a, const void *b) {
return ((PathEdge *) a)->cost - ((PathEdge *) b)->cost;
}
int main(void)
{
int nlines,i;
char r;
int ecost,ebegin,eend;
scanf("%d",&nlines);
PathEdge edges[nlines+1];
for(i=0;i<nlines;i++)
{
scanf("%d, %d, %dn",&ebegin, &eend, &ecost);
edges[i].begin = ebegin;
edges[i].end = eend;
edges[i].cost = ecost;
struct town
{
struct town *north;
int name[25000];
};
struct town *root, *current;
root = malloc(sizeof(struct town));
root->north = NULL;
strcpy (root->name,ecost);
current = malloc(sizeof(struct town));
current->north = root;
strcpy (current->name,ecost);
}
printf("Please enter a node that you want to examine. If you want to exit, please press 'X'.n");
scanf("%c",&r);
switch(r)
{
case 'X':
case 'x':
printf("You entered a wrong value. Gomen. Try againn.");
break;
default:
if((0<r)&&(r<25000))
{
printf("You have accessed node %dn",r);
printf("Its neighboring nodes are %dn",edges[r].cost);
printf("Its neighboring nodes are %dn",edges[i].cost);
}
else
{
printf("Invalid input again. Please do try again. Thanksn");
}
break;
}
return 0;
}
And there are warnings...
"passing argument 1 of strcpy from incompatible pointer type"
"passing argument 2 of strcpy makes pointer from integer without a cast"
expected char*__ restrict __ but argument is of type 'int'
plus when I inputted that 25000 lines of text, segmentation fault happens. Please help. Thank you!
strcpy is for copying strings (i.e. zero terminated byte char "arrays"), you maybe should use memcpy instead.
Or if you just want to assign a single integer to one element in the array, use plain assignment:
current->name[someIndex] = ecost;
Or, maybe you intend that thename member should be a string? Then you should be using an array of characters and not integers. And you need to convert integer values to strings, using e.g. sprintf:
sprintf(current->name, "%d", ecost);
you can convert the integer to string using itoa and copy the string into root->name.
char str[20];
itoa(ecost, str, 10);
strcpy(root->name, str);
You did not state your exact issue so I am assuming you are overwhelmed and in that case you should try partitioning your implementation into functions so that you can work on isolated problems instead of a web of interconnected problems.
Here is one example:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct graph {
int begin;
int end;
int cost;
} PathEdge;
const char * GenerateInput()
{
static char local[2000];
static int last = 0;
int a, b, c;
a = last++;
b = last++;
c = last++;
sprintf_s(local, 2000, "%i %i %i", a, b, c);
return local;
}
void PathEdgeInitializeFromString(PathEdge * edge, const char * str)
{
sscanf_s(str, "%d %d %dn", &edge->begin, &edge->cost, &edge->end);
}
void QueryAndPrint(PathEdge * edges, int edges_n)
{
printf("Enter a number from 1 to %i: ", edges_n);
int index = 0;
scanf_s("%i", &index);
--index;
if (index < 0 || !(index < (edges_n)))
printf("Error");
else
printf("%i, %i, %i\n", edges[index].begin, edges[index].cost, edges[index].end);
}
int main() {
PathEdge edges[25000];
for (int i = 0; i < 25000; ++i)
{
const char * line = GenerateInput();
PathEdgeInitializeFromString(edges + i, line);
}
QueryAndPrint(edges, 25000);
return 0;
}
Related
#include<stdio.h>
#include<stdlib.h> //libraries
#include<string.h>
#define ARRAY_SIZE 4 //define the array size is 4
Declare a Person structure containing the following two data members: name and age.
struct Person
{
char name[20];
int age;
};
Define fillPersons function that takes an empty array of Persons, and fills the array.
void fillPersons(struct Person * myPs);
For function using
struct Person p[ARRAY_SIZE];
Define searchPerson function that takes an array of Persons, and the name to search for. The function will return the corresponding age if the person is found, -1 otherwise.
int searchPerson(struct Person * myPs, char * myName);
Define printPersons function that takes an array of Persons, and prints the content of the array.
void printPersons(struct Person * myPs);
Main Fuction
int main()
{
struct Person p[ARRAY_SIZE];
int a;
int isFound;
char myName[20];
Switch case for user interface
do
{
printf("1)FILL ARRAY\n");
printf("2)SEARCH BY NAME\n");
printf("3)PRINT ARRAY\n");
printf("4)EXIT\n");
printf("Search Operation:");
scanf_s("%d", &a);
switch (a)
{
case 1:fillPersons(p); break;
I write the main part of searching but i cant fill the function.
case 2:printf("\Give the name to search for:");
scanf_s("%s", &myName);
isFound = searchPerson(p, myName);
if (isFound == -1)
{
printf("%s not avaible in the array. \n", myName);
}
else
{
printf("The age of %s is %d.\n", myName, isFound);
}
break;
After this part it is okay to read names and ages but cant do it searching part.
case 3:printPersons(p); break;
case 4:printf("\nProgram exits ..."); exit(0);
}
} while (a != 4);
system("pause");
return 0;
}
It is okay this scanf part
void fillPersons(struct Person * myPs)
{
int i;
for (i = 0; i < 4; i++)//defining 4 person i<4
{
scanf_s("%20s", p[i].name,_countof(p[i].name));//if i dont do _coutof
scanf_s("%d", &p[i].age); // i get null.ptr error
} // on visiual studio
}
Printing the student names and ages
void printPersons(struct Person * myPs)
{
int i;
for (i = 0; i < 4; i++)
{
printf("%s %d", p[i].name, p[i].age);
}
}
But i dont know how to fill with inside on fuction?
int searchPerson(struct Person * myPs, char * myName)
THE OUTPUT SHOULD BE LIKE THIS
Seems the function you are missing is strcmp to compare two strings.
It could be like:
int searchPerson(struct Person * myPs, char * myName)
{
int i;
for (i = 0; i < ARRAY_SIZE; i++)
{
if (strcmp(myPs[i].name, myName) == 0)
{
return myPs[i].age;
}
}
return -1;
}
In general notice:
When you pass the array to a function as struct Person * myPs, you must use myPs inside the function. Further you should use the defined array size instead of hard coding a 4.
So your printPersons should be:
void printPersons(struct Person * myPs)
{
int i;
for (i = 0; i < ARRAY_SIZE; i++)
{
printf("%s %d", myPs[i].name, myPs[i].age);
}
}
Same applies to fillPersons
First thing, you put in your question all the functions except the one that is giving you problems: searchPerson.
Then, your error is with this instruction:
scanf_s("%s", &myName);
Accordingly that you declared myName as a char pointer, this way, you're assigning the string to the address of myName, not to the memory cells it's pointing to.
Instead, this should be:
scanf_s("%s", myName);
I supposed to perform a project which allocate N bytes of memory of struct person
and scanning f every person's name initial_money and some other variables
the problem for me when i run the code is that it is terminating at some point of taking input process and i don't why
also this problem faced me yesterday in code forces contest
#include <stdio.h>
#include <stdlib.h>
struct person
{
char name[15];
int initial_money;
int g;
int final_money;
int money;
};
int main()
{
int NP,i,j;
char target1[15];
scanf("%d",&NP);
struct person *p=malloc(NP*sizeof(struct person));
for(i=0;i<NP;i++)
{
scanf("%s",(p+i)->name);
}
for(i=0;i<NP;i++)
{
scanf("%s",target1);
for(j=0;j<NP;j++)
{
if((p+j)->name==target1)
{
scanf("%d%d",(p+j)->initial_money,(p+j)->g);
(p+j)->final_money=(p+j)->initial_money%(p+j)->g;
}
}
}
for(i=0;i<NP;i++)
{
printf("%s %d %d %d",(p+i)->name,(p+i)->initial_money,(p+i)->g,(p+i)->final_money);
}
return 0;
}
The scanf function need pointers for inputed values.
The line:
scanf("%d%d",(p+j)->initial_money,(p+j)->g);
Should be:
scanf("%d %d",&(p+j)->initial_money,&(p+j)->g);
When comparing strings you usually can't compare pointers directly:
if((p+j)->name==target1)
shoul be:
if(strcmp((p+j)->name, target1) == 0)
I have to build a hash table data structure for this project, which I have done it in other files. For some reason when I compile my program and I get error, which is regarding initialization function (TableCreate();) of hash table. When I remove this part of the code from main function and execute, it works fine but then I get segfault when i try to add something to the hash table.
I believe my hash table code has nothing to do with this errors because my hash table code is based upon examples of Hash table code which was provided to us by our professor
I'm using GCC compiler.
Please help me solve this issue.
Error Message
src/sshell.c: In function âmainâ:
src/sshell.c:34: warning: implicit declaration of function âTableCreateâ
src/sshell.c:34: warning: assignment makes pointer from integer without a cast
sshell.c
#include "parser.h"
#include "shell.h"
#include "hash_table.h"
#include "variables.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(void){
char input[1000], sInput[1000]; // String to get user input
int count=1, len; // num=0;
struct Table *t;
t = TableCreate(); //create the table
int while_track;
FILE *ptr_file;
ptr_file =fopen(".simpleshell_history","a");
fclose(ptr_file);
printf("\nWelcome to the sample shell! You may enter commands here, one\n");
printf("per line. When you're finished, press Ctrl+D on a line by\n");
printf("itself. I understand basic commands and arguments separated by\n");
printf("spaces, redirection with < and >, up to two commands joined\n");
printf("by a pipe, tilde expansion, and background commands with &.\n\n");
printf("\npssh$ ");
while (fgets(input, sizeof(input), stdin)) {
strcpy(sInput, input);
len = strlen(input);
if( input[len-1] == '\n' ){
input[len-1] = '\0';
}
while_track = 1; // used to keep track of loop
while (while_track == 1){
count+=1;
if (strcmp(input, "history")==0){
while_track = History(); // print history function call
}else if (strcmp(input, "!!")==0){
while_track = Previous(input); // execute previous function call
}else if (strncmp(input, "!",1)==0){ // !string and !number sort
if(isdigit(input[1])){
while_track = Number(input);
} else {
while_track = String(input);
}
}else { // if the user entry was not any of specfic comnnad then pass the command to parse to execute
other(input,t);
parse(input);
while_track = 0;
}
}
HistoryFile(sInput); // A function call to recode commands entered by the user into a file
printf("\npssh$ ");
}
return 0;
}
hash_table.c
#include "hash_table.h"
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
void feedData(char * var, char * val, struct Table *t){
//const char * key=0;
printf("\n In FeedData Function\n");
Table_add(t, var, val);
printf("\nInside Feed Function -- Veriable: %s Value: %s\n",var, val);
}
unsigned int hash(const char *x) {
printf("\n In Hash\n");
int i;
unsigned int h = 0U;
printf("\n In Hash - Before for loop\n");
for (i=0; x[i]!='\0'; i++)
printf("\n In Hash - In for loop %d \n", i);
h = h * 65599 + (unsigned char)x[i];
printf("\n In Hash - In for loop - after calculation \n");
unsigned int g;
g = h % 1024;
printf("\n In Hash - In for loop - before return: %u \n",g);
return g;
}
struct Table *Table_create(void) {
printf("\n In Table_create\n");
struct Table *t;
t = (struct Table*)calloc(1, sizeof(struct Table));
return t;
}
void Table_add(struct Table *t, const char *key, char * val){
printf("\n In Table_add\n");
struct Node *p = (struct Node*)malloc(sizeof(struct Node));
int h = hash(key);
printf("\n In Table_add - after hash key\n");
//p->key = *key;
strcpy(p->key,key);
printf("\n In Table_add - after first key\n");
strcpy(p->value,val);
printf("\n In Table_add - after Value\n");
p->next = t->array[h];
printf("\n In Table_add - after p->next\n");
t->array[h] = p;
printf("\n In Table_add - after t->array[h] = p\n");
}
/*
int Table_search(struct Table *t, const char *key, int *value){
struct Node *p;
int h = hash(key); //---------------------------------------------------------------------
for (p = t->array[h]; p != NULL; p = p->next)
if (strcmp(p->key, key) == 0) {
*value = p->value;
return 1;
}
return 0;
}
*/
/*
void Table_free(struct Table *t) {
struct Node *p;
struct Node *nextp;
int b;
for (b = 0; b < BUCKET_COUNT; b++)
for (p = t->array[b]; p != NULL; p = nextp) {
nextp = p->next;
free(p);
}
free(t);
}
*/
hash_table.h file code
#ifndef HASH_TABLE_H
#define HASH_TABLE_H
struct Table *Table_create(void);
void Table_add(struct Table *t, const char *key, char * val);
unsigned int hash(const char *x);
void feedData(char * var, char * val, struct Table *t);
enum {BUCKET_COUNT = 1024};
struct Node {
char key[1000];
char variable[1000];
char value[1000];
struct Node *next;
};
struct Table {
struct Node *array[BUCKET_COUNT];
};
#endif
Warning 1: You are calling TableCreate while your function name is Table_create
Warning 2: After looking at new identifier followed by (, compiler assumes it is a function that takes variable number of arguments and returns int.
I have come across this wierd and mysterous (at least to me) error that I am finding a very hard time finding. It gives me an error at the line where I call my function input(student_list1[MAX], &total_entries); where the compiler says:
incompatible type for agument 1 in 'input'
What am I doing wrong here? I sense it something very simple and stupid but I have gone through the code several times now without any avail.
#define MAX 10
#define NAME_LEN 15
struct person {
char name[NAME_LEN+1];
int age;
};
void input(struct person student_list1[MAX], int *total_entries);
int main(void)
{
struct person student_list1[MAX];
int total_entries=0, i;
input(student_list1[MAX], &total_entries);
for(i=0; i<total_entries; i++)
{
printf("Student 1:\tNamn: %s.\tAge: %s.\n", student_list1[i].name, student_list1[i].age);
}
return 0;
} //main end
void input(struct person student_list1[MAX], int *total_entries)
{
int done=0;
while(done!=1)
{
int i=0;
printf("Name of student: ");
fgets(student_list1[i].name, strlen(student_list1[i].name), stdin);
student_list1[i].name[strlen(student_list1[i].name)-1]=0;
if(student_list1[i].name==0) {
done=1;
}
else {
printf("Age of student: ");
scanf("%d", student_list1[i].age);
*total_entries++;
i++;
}
}
}
struct person student_list1[MAX] in the function argument is actually a pointer to struct person student_list1.
student_list1[MAX] you passed is a (out of bound) member of the array struct person student_list1[MAX]. Valid array index shoudl be between 0 to MAX - 1.
Change it to:
input(student_list1, &total_entries);
Note that here the array name student_list1 is automatically converted to a pointer to student_list1[0].
There are many things wrong with the code; this is my attempt at making it somewhat more robust:
#include <stdio.h>
#include <string.h>
#define MAX 10
#define NAME_LEN 15
// use a typedef to simplify code
typedef struct person {
char name[NAME_LEN];
int age;
} person_t;
// size qualifier on student_list is redundent and person_t* does the same
void input(person_t *student_list, int *total_entries);
int main(void)
{
person_t student_list[MAX];
int total_entries, i;
// pass array and not the non-existent 'student_list[MAX]' element
input(student_list, &total_entries);
for(i=0; i<total_entries; i++)
{
// age is an int, not a string so use %d
printf("Student 1:\tName: %s.\tAge: %d.\n", student_list[i].name, student_list[i].age);
}
return 0;
} //main end
void input(person_t *student_list, int *total_entries)
{
int done = 0, i = 0;
*total_entries = 0;
while (i < MAX) {
printf("Name of student: ");
// use NAME_LEN instead of strlen(list[i].name) because latter is
// probably not initialized at this stage
if (fgets(student_list[i].name, NAME_LEN, stdin) == NULL) {
return;
}
// detect zero-length string
if (student_list[i].name[0] == '\n') {
return;
}
printf("Age of student: ");
scanf("%d", &student_list[i].age);
// read the newline
fgetc(stdin);
*total_entries = ++i;
}
}
input(student_list1[MAX], &total_entries); shoud be input(student_list1, &total_entries);.
In C,
void input(struct person student_list1[MAX], int *total_entries);
equals
void input(struct person *student_list1, int *total_entries);
I am trying to learn about structs, pointers, and dynamic arrays in C. I don't understand how to create a dynamic array of structs using pointers. My code doesn't work, and I don't know what's wrong with it. I have seen several examples of dynamic arrays, but non with structs. Any help would be appreciated. Please give some explanation, not just code snippets as I do want to understand not just solve this problem.
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
struct *struct_array;
int i,m,n,p;
struct data
{
char inputA[20];
char inputB[20];
};
struct data get_data()
{
struct data thisdata;
printf("Please enter input A\n");
scanf("%s", thisdata.inputA);
printf("Please enter input B\n");
scanf("%s", thisdata.inputB);
return thisdata;
}
void Output(struct data struct_array, int n)
{
int index = 0;
for(i = 0; i<n ;i++)
{
printf("%s ", struct_array[i].inputA);
printf("%s ", struct_array[i].inputB);
}
}
void resizeArray(int n)
{
struct_array = (int*)realloc(n*sizeof(int));
}
void mainMenu()
{
printf("Please select from the following options:\n");
printf("1: Add new students to database\n");
printf("2: Display current student database contents\n");
printf("3: exit the program\n");
scanf("%d", &p);
if(p == 1)
{
printf("Please enter the number of students to register:\n");
scanf("%d", &n);
resizeArray(n);
for(i = n; i<n ;i++)
{
struct_array[i] = get_data();
}
}
else if(p == 2)
{
Output(struct_array, n);
}
else
{
free(struct_array);
exit(0);
}
}
int main()
{
struct_array = (int*)realloc(2*sizeof(int));
mainMenu();
}
You have several errors in your source code:
struct *struct_array; (l. 5)
What does it mean? Did you want to write struct data *struct_array?
printf("%s ", struct_array[i].inputA); (l.32 & l. 33)
The argument struct_array masks the global declaration, and it is not an array. Why did you add this argument?
struct_array = (int *)realloc(n * sizeof(int)); (l. 39)
You have forgotten an argument. Did you want to use malloc instead? Besides, the cast is not necessary (and incorrect!).
Unless you are using an hosted environnment and C99/C11, you should return a value from main.
Your variable index is not used. Why did you declare it?
for(i = n; i < n; i++) (l. 53)
You won't have any iteration here...
The following code works as expected.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* TODO: Avoid global variables. */
struct data *struct_array;
struct data {
char inputA[20];
char inputB[20];
};
/*
* TODO: Try to avoid passing your structure (40 bytes + padding)
* without pointer.
*/
struct data get_data(void)
{
struct data thisdata;
printf("Please enter input A\n");
/* TODO: Avoid using `scanf` for human inputs. */
scanf("%s", thisdata.inputA);
printf("Please enter input B\n");
scanf("%s", thisdata.inputB);
return thisdata;
}
void Output(size_t n)
{
size_t i;
for (i = 0; i < n; i++) {
printf("%s ", struct_array[i].inputA);
printf("%s ", struct_array[i].inputB);
}
}
void resizeArray(size_t n)
{
/* TODO: Handle reallocations errors. */
struct_array = realloc(struct_array, n * sizeof *struct_array);
}
void mainMenu(void)
{
size_t i, n;
int p;
/* TODO: Use a loop ? */
printf("Please select from the following options:\n");
printf("1: Add new students to database\n");
printf("2: Display current student database contents\n");
printf("3: exit the program\n");
scanf("%d", &p);
switch (p) {
case 1:
printf("Please enter the number of students to register:\n");
scanf("%u", &n);
resizeArray(n);
for (i = 0; i < n; i++)
struct_array[i] = get_data();
break;
case 2:
Output(n);
break;
}
}
int main(void)
{
struct_array = malloc(2 * sizeof(int));
mainMenu();
free(struct_array);
return 0;
}
Your definition
struct *struct_array;
is erroneous. You must use the name of your type, the data.
struct data *struct_array;
This way you can allocate the array
struct_array = malloc(MaxNumElements * sizeof(struct data));
and later you should free the memory
free(struct_array);
EDIT: Type definition must occur before the var declaration.
struct data ....
struct data* your_variable;
P.S. If you do not want to type struct keyword each time you use the data type, use the typedef:
typedef struct data_s
{
char inputA[20];
char inputB[20];
} data;
Do you know how to use typedef?
I would suggest it, makes your code easier to understand and you won't have to be typing the word struct a thousand times. Also you could treat the new type similar to the primitive types (ints, chars, etc), just don't forget to use the dot (.) to access the individual fields you might want.
You could type for instance:
typedef struct{
char inputA[20];
char inputB[20];
} data;
Now you could declare variables like this:
data data_variable;
data *pointer_to_data;
And to you could allocate memory as follows:
pointer_to_data = (data*) malloc(sizeof(data)* N);
where N is the amount of struct data you want to allocate. Same works for realloc.
struct_array = (int*)realloc(2*sizeof(int));
By the above statement you are trying to assign address of an int to a pointer of type struct data.
You need to use:
struct_array = (struct data*)realloc(2*sizeof(struct data));