string.h and strncpy with pointers in C - c

I'm trying to create a user input created list that contains a structure with one int and two strings. But i seem unable to use correctly the strncopy from the string.h.
I'm supposed to use the order of the parameters like:
1. name of pointer
2. string to be copied
3. string length
The error i get says that 'name' and 'lastn' which are strings are not declared...so what am i missing here?
CODE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stats
{
int age;
char name[25];
char lastn[25];
struct stats *next;
};
void fill_structure(struct stats *s);
struct stats *create(void);
int main()
{
struct stats *first;
struct stats *current;
struct stats *new;
int x = 5;
//create first structure
first = create();
current = first;
for(x=0; x<5; x++)
{
if(x==0)
{
first = create();
current = first;
}
else
{
new = create();
current->next = new;
current = new;
}
fill_structure(current);
}
current->next = NULL;
current = first; //reset the list
while(current)
{
printf("Age %d, name %s and last name %s", current->age, strncpy(current->name, name, strlen(name)), strncpy(current->lastn, lastn, strlen(lastn)));
}
return(0);
}
//fill a structure
void fill_structure(struct stats *s)
{
printf("Insert Age: \n");
scanf("%d", &s->age);
printf("Insert Name: \n");
scanf("%s", &s->name);
printf("Insert Last Name: ");
scanf("%s", &s->lastn);
s->next = NULL;
}
//allocate storage for one new structure
struct stats *create(void)
{
struct stats *baby;
baby = (struct stats *)malloc(sizeof(struct stats));
if( baby == NULL)
{
puts("Memory error");
exit(1);
}
return(baby);
};

strncpy(current->name, name, strlen(name))
^ ^
You didn't declare any object named name. In your program the only name identifier is the name member of struct stats structure type.

The following line uses name and lastn, which are not defined.
printf("Age %d, name %s and last name %s", current->age, strncpy(current->name, name, strlen(name)), strncpy(current->lastn, lastn, strlen(lastn)));
It's not clear what you are trying to accomplish by the calls to strncpy here. It will be sufficient to use:
printf("Age %d, name %s and last name %s", current->age, current->name, current->lastn);
Also, while(current) will run for ever since you are not changing current in the loop. Use:
while(current)
{
printf("Age %d, name %s and last name %s", current->age, current->name, current->lastn);
current = current->next; // Need this
}
In fill_structure, instead of:
scanf("%s", &s->name);
scanf("%s", &s->lastn);
use
scanf("%s", s->name); // Drop the &
scanf("%s", s->lastn);

Related

Pointer's value changes without modifying

I'm studying linked list and try to implement some basic function.
My code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LEN_NAME 5
#define INSERT_NODE 1
#define APPEND_NODE 2
#define DEL_HEAD 3
#define DEL_TAIL 4
#define SHOW_LIST 5
struct people {
int id;
char name[MAX_LEN_NAME];
struct people *next;
};
typedef struct people people_list;
static void node_insert(people_list** head_ref, int id, const char* name);
static void node_append(people_list** head_ref, int id, const char* name);
static void node_del_head(people_list** head_ref);
static void node_del_tail(people_list** head_ref);
static void node_show(people_list** head_ref);
static void node_insert(people_list** head_ref, int id, const char* name)
{
people_list* new_node = NULL;
new_node = malloc(sizeof(people_list));
memset(new_node, 0, sizeof(people_list));
if (new_node == NULL) {
printf("Fail to allocate memory for new node\n");
exit(1);
}
new_node->id = id;
memcpy(new_node->name, name, sizeof(name));
new_node->next = *head_ref;
*head_ref = new_node;
}
static void node_append(people_list** head_ref, int id, const char* name)
{
return;
}
static void node_del_head(people_list** head_ref)
{
return;
}
static void node_del_tail(people_list** head_ref)
{
return;
}
static void node_show(people_list** head_ref)
{
people_list* current = NULL;
current = *head_ref;
if (current == NULL) {
printf("Empty list, nothing to show\n");
return;
}
printf("Elements in the list: \n");
while (current != NULL) {
printf("id = %d, name = %s\n", current->id, current->name);
current = current->next;
if (current == NULL) {
printf("This is the last element\n");
}
}
}
int main(void)
{
people_list* list = NULL;
#if 0
people_list* second = NULL;
people_list* third = NULL;
list = malloc(sizeof(people_list));
memset(list, 0, sizeof(people_list));
second = malloc(sizeof(people_list));
memset(second, 0, sizeof(people_list));
third = malloc(sizeof(people_list));
memset(third, 0, sizeof(people_list));
list->id = 1;
memcpy(list->name, "duc", sizeof("duc"));
list->next = second;
second->id = 2;
memcpy(second->name, "hy", sizeof("hy"));
second->next = third;
third->id = 3;
memcpy(third->name, "bo", sizeof("bo"));
third->next = NULL;
#endif
char id;
char name[MAX_LEN_NAME] = {0};
int option = 0;
while (1) {
printf("******************\n");
printf("1: Insert new node\n");
printf("2: Append new node\n");
printf("3: Delete head node\n");
printf("4: Delete tail node\n");
printf("5: Show list\n");
printf("Insert your choice: ");
scanf("%d", &option);
switch (option) {
case INSERT_NODE:
printf("debug: list=%08Xh\n", list);
printf("Enter id's value: ");
scanf("%d", &id);
printf("Enter name: ");
scanf("%s", name);
printf("debug: list=%08Xh\n", list);
node_insert(&list, id, name);
memset(name, 0, MAX_LEN_NAME);
break;
case APPEND_NODE:
printf("Enter id's value: ");
scanf("%d", &id);
printf("Enter name: ");
scanf("%s", name);
node_insert(&list, id, name);
memset(name, 0, MAX_LEN_NAME);
break;
case DEL_HEAD:
node_del_head(&list);
break;
case DEL_TAIL:
node_del_tail(&list);
break;
case SHOW_LIST:
node_show(&list);
break;
default:
printf ("Invalid input, closing program...\n");
exit(0);
break;
}
}
}
How I test:
Insert first node (1, jon)
Insert second node (2, may)
Show list => Only second node is printed.
I found that, the second->next does not point to the first node, it points to a NULL node. I keep debugging as below
case INSERT_NODE:
printf("debug: list=%08Xh\n", list);
printf("Enter id's value: ");
scanf("%d", &id);
printf("Enter name: ");
scanf("%s", name);
printf("debug: list=%08Xh\n", list);
node_insert(&list, id, name);
memset(name, 0, MAX_LEN_NAME);
break;
and the console log is
Insert your choice: 1
debug: list=001F29A8h => This is the address holding value of the first node
Enter id's value: 2
Enter name: may
debug: list=00000000h => The value of list is clear ???
As you can see, the value of the ponter list changes without modifying. Please help me to fix this. Thank you.
As pointed out in the comments, with scanf("%d", &id);, %d is expecting an int *. Change
char id;
char name[MAX_LEN_NAME] = {0};
to
int id;
char name[MAX_LEN_NAME] = {0};
Otherwise you invoke Undefined Behaviour by passing an unexpected type to scanf.
With good compiler warnings, we get the following:
warning: 'memcpy' call operates on objects of type 'const char'
while the size is based on a different type 'const char *'
[-Wsizeof-pointer-memaccess]
memcpy(new_node->name, name, sizeof(name));
When the sizeof operator is used on a pointer (in this case, a const char *) the result is the size of the pointer in bytes, not the object it points to.
Change this function call to
memcpy(new_node->name, name, sizeof new_node->name);
/* OR memcpy(new_node->name, name, MAX_LEN_NAME); */
or more appropriately, use strcpy
strcpy(new_node->name, name);
Suggest changing #define MAX_LEN_NAME 5 to something more reasonable like #define MAX_LEN_NAME 128.
At the same time, scanf("%s", name); should be changed to have a field width specifier that limits the length of the input read, to avoid buffer overflows. This should be the buffer size minus one (e.g., scanf("%127s", name);).
Additionally, the return value of scanf should not be ignored. Ensure it is the expected number of successful conversions, and otherwise handle failure. E.g.,
if (2 != scanf("%d%u", &si, &us)) {
fprintf(stderr, "Failed to read inputs.\n");
exit(EXIT_FAILURE);
}
Aside: These function calls
people_list* new_node = NULL;
new_node = malloc(sizeof(people_list));
memset(new_node, 0, sizeof(people_list));
can be simplified with calloc
people_list *new_node = calloc(1, sizeof *new_node);

Weird characters in string with C (Structs, pointers, and strings)

Hi I'm creating a linked list that holds students' information.
However, when displaying the string variables of the student struct, it displays characters other than the strings that it's supposed to display. Here is the snippet from my code (I cut out the code unrelated to my problem):
# include <stdio.h>
# include <stdlib.h>
struct Student {
int student_number[2];
char *last;
char *first;
char *course;
int year;
int age;
char sex;
int grade;
struct Student * next;
};
typedef struct Student Student;
struct SLList {
Student * head;
Student * tail;
int size;
};
typedef struct SLList SLList;
void initList(SLList * list){
list->head = 0;
list->tail = 0;
list->size = 0;
}
Student * getStudent(SLList * list, int index) {
Student * current = list->head;
for (int i = 0; i < index; i ++) {
current = current->next;
}
return current;
}
Student * createStudent(int * number, char *last, char *first, char * course, int year, int age, char sex, int grade){
Student * student = (Student *) malloc(sizeof(Student));
student->student_number[0] = number[0];
student->student_number[1] = number[1];
student->last = last;
student->first = first;
student->course = course;
student->year = year;
student->age = age;
student->sex = sex;
student->grade = grade;
student->next = 0;
return student;
}
void enrolStudent(SLList * list, int index){
Student * student;
int i, found = 1;
int student_number[2];
char last[15];
char first[15];
char course[15];
int year;
int age;
char sex;
int grade;
printf("Student Number: ");
scanf("%i-%i", &student_number[0], &student_number[1]);
printf("Last Name: ");
scanf("%s", last);
printf("First Name: ");
scanf("%s", first);
printf("Course: ");
scanf("%s", course);
printf("Year: ");
scanf("%i", &year);
printf("Age: ");
scanf("%i", &age);
printf("Sex [M or F]: ");
scanf(" %c", &sex);
printf("Final Grade: ");
scanf("%i", &grade);
Student * toInsert = createStudent(student_number, last, first, course, year, age, sex, grade);
if (index == 0){
toInsert->next = list->head;
list->head = toInsert;
}
if (index == list->size){
if (list->tail != 0) {
list->tail->next = toInsert;
}
list->tail = toInsert;
}
list->size ++;
return;
}
void showStudents(SLList * list, int index) {
Student * student = getStudent(list, index);
printf("\n");
printf("Student Number: %i-%i\n", student->student_number[0], student->student_number[1]);
printf("Last Name: %s\n", student->last);
printf("First Name: %s\n", student->first); //! error in printing strings
printf("Course: %s\n", student->course);
printf("Year Level: %i\n", student->year);
printf("Age: %i\n", student->age);
printf("Sex: %c\n", student->sex);
printf("Final Grade: %i\n", student->grade);
printf("\n");
}
int main(){
int choice = 0;
int rtn = 0;
SLList students;
initList(&students);
printf("What do you want to do?\n");
printf("1. Enrol a student\n");
[...]
printf("4. Display all student/s\n");
for(;;){
printf("\nEnter a number: ");
rtn = scanf("%d", &choice);
if (choice == 1) {
enrolStudent(&students, students.size);
} else if (choice == 4) {
int i;
for (i = 0; i < students.size; i ++){
showStudents(&students, i);
}
printf("Displaying %i of %i student(s)\n", i, students.size);
}
[...]
}
I believe that I need to allocate memory for the char * variables of the struct, but I don't know how it should go.
Hope to get some help. Thanks!
you are passing local variable address to createStudent and simply assigning this to internal pointers that's wrong.
you can do is use something like an strdup call as below
student->last = strdup(last);
student->first = strdup(first);
student->course = stddup(course);
or allocate space to last, first and course and copy the string
Your assumption is correct: You assigned pointers to stack objects to your list elements. So the content is likely to be overwritten on the course of further execution of the program, which gives you the weird characters in the output further down the road.
The correct way would be to allocate memory for the strings during createStudent which is done through malloc or calloc of minimum the length of the string. And you already have an example there in your function, so I'm a bit surprised that you stated you don't know how to do that. Another possibility is to call strdup for that purpose which basically does exactly the combination of allocation and string copy.
Oh and one more remark: Please make it a habit from the beginning of your career that you clean up after yourself. Meaning: Whatever you allocate, deallocate it after usage. In your case: If you have a createStudent function, create a destroyStudent function. If you have a linked list somewhere, free it before exitting the program. Picking that habit up early will save you from memory leaks in the future.

Writing data from a linked list to a txt file in C

I created this program that first asks how many pets you own, then stores the name and age of each pet in a struct (all using linked lists).
My question is: I'm trying to write the data into a .txt file using a procedure writeToFile() but upon execution, the .txt file does not contain any data. I don't understand why?
This is my code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
char *name;
int age;
struct Node *next;
};
struct Node * petRecord;
struct Node * newRecord;
void printPetRecord()
{
while(petRecord != NULL)
{
printf("Name of Pet: %s\n", petRecord->name);
printf("Age of Pet: %d\n", petRecord->age);
petRecord = petRecord->next;
}
}
void writeToFile()
{
FILE * fptr;
fptr = fopen("petnames.txt", "w");
if(fptr==NULL)
{
printf("Error\n");
}
else
{
while(petRecord != NULL)
{
fprintf(fptr, "\nPet Name: %s\nAge: %d\n", petRecord->name, petRecord->age);
petRecord = petRecord->next;
}
}
fclose(fptr);
}
int main()
{
int count, i;
printf("How many pets do you have? ");
scanf("%d", &count);
for(i=0; i<count; i++)
{
if(i==0)
{
petRecord = malloc(sizeof(struct Node));
newRecord = petRecord;
}
else
{
newRecord->next = malloc(sizeof(struct Node));
newRecord = newRecord->next;
}
newRecord->name = malloc(50*sizeof(char));
printf("Name of Pet: ");
scanf("%s", newRecord->name);
printf("Age of Pet: ");
scanf("%d", &newRecord->age);
}
newRecord->next = NULL;
printf("\n\n");
printPetRecord();
writeToFile();
}
Your function printPetRecord() leaves your pointer set to null.
Inside printPetRecord() make something like this:
struct Node * iterator = petRecord;
and then itertae using iterator.
#include <stdio.h>
#include <stdlib.h>
struct Node {
char *name;
int age;
struct Node *next;
};
struct Node * petRecord;
struct Node * newRecord;
void printPetRecord()
{
struct Node * iterator = petRecord;
while(iterator != NULL)
{
printf("Name of Pet: %s\n", iterator->name);
printf("Age of Pet: %d\n", iterator->age);
iterator=iterator->next;
}
}
void writeToFile()
{
FILE * fptr;
fptr = fopen("petnames.txt", "w");
struct Node * iterator = petRecord;
if(fptr==NULL)
{
printf("Error\n");
}
else
{
while(iterator!= NULL)
{
fprintf(fptr, "\nPet Name: %s\nAge: %d\n", iterator->name, iterator->age);
iterator= iterator->next;
}
}
fclose(fptr);
}
int main()
{
int count, i;
printf("How many pets do you have? ");
scanf("%d", &count);
for(i=0; i<count; i++)
{
if(i==0)
{
petRecord = malloc(sizeof(struct Node));
newRecord = petRecord;
}
else
{
newRecord->next = malloc(sizeof(struct Node));
newRecord = newRecord->next;
}
newRecord->name = malloc(50*sizeof(char));
printf("Name of Pet: ");
scanf("%s", newRecord->name);
printf("Age of Pet: ");
scanf("%d", &newRecord->age);
}
newRecord->next = NULL;
printf("\n\n");
printPetRecord();
writeToFile();
}
Execution:
> gcc -o main main.c
> ./main
How many pets do you have? 2
Name of Pet: a
Age of Pet: 2
Name of Pet: b
Age of Pet: 3
Name of Pet: a
Age of Pet: 2
Name of Pet: b
Age of Pet: 3
> cat petnames.txt
Pet Name: a
Age: 2
Pet Name: b
Age: 3
After 3 years 7 months, somehow I got this question while solving my problem to write the data of a linked list to a .txt file. I came here to seek the solution of my problem, but this question hasn't accepted any answers. So here I'll try to answer this question.
There's no need for global variables in the program.
Send some arguments to the functions in the program, it'll make your task a lot easier.
While iterating inside those functions you are losing your head structure variable by doing this petRecord = petRecord->next and inside main newRecord = newRecord->next. This is happening because of the Global variables. So, to avoid this you need to declare each time, inside the called function a local pointer variable of type struct Node.
Don't do this: newRecord->name = malloc(50*sizeof(char));, if you know the exact size of char array instead of doing this, modify your struct template to char name[50]. It is a lot easier than using a pointer and dynamic allocation because in the latter case you need to take extra care and precaution.
Open file in which the data is to be written inside main() function and send it to the function writeToFile().
Extra care should be taken while dealing with strings.
It is worth checking errors while allocating memory or opening files. So each time when you do any of these in your program, it's better to check for any kinda error that occurred while the operation.
Why don't you try this program:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
char name[50];
int age;
struct Node *next;
}Node;
// user-defined functions
void printPetRecord(Node *head);
void writeToFile(FILE *fptr, Node *head);
// main()
int main(void)
{
int count, i;
Node *petRecord, *newRecord;
FILE *fp;
if( (petRecord = malloc(sizeof(Node))) == NULL )
{
fprintf(stderr, "Unable to allocate memory.\n");
exit(2);
}
newRecord = petRecord;
printf("How many pets do you have? ");
scanf("%d", &count);
for(i = 0; i < count; i++)
{
printf("Name of Pet: ");
scanf("%50s", newRecord->name);
printf("Age of Pet: ");
scanf("%d", &newRecord->age);
if(i == count-1)
{
newRecord->next = NULL;
}
else
{
if( (newRecord->next = malloc(sizeof(Node))) == NULL)
{
fprintf(stderr, "Memory Unavailable.\n");
exit(3);
}
}
newRecord = newRecord->next;
}
printf("\n\n");
// Modified arguments
printPetRecord(petRecord);
// Open file before sending to writeToFile
if(!(fp = fopen("petname.txt", "w")))
{
fprintf(stderr, "Unable to open file \"petname.txt\"\n");
exit(1);
}
// Modified arguments
writeToFile(fp, petRecord);
fclose(fp);
return 0;
}
// function to print linked_list
void printPetRecord(Node *head)
{
if(head->next != NULL)
{
printf("Name of Pet: %s\nAge of Pet: %d\n", head->name, head->age);
printPetRecord(head->next);
}
else
printf("Name of Pet: %s\nAge of Pet: %d\n", head->name, head->age);
}
// function to print list to file
void writeToFile(FILE *fptr, Node *head)
{
if(head->next != NULL)
{
fprintf(fptr, "\nPet Name: %s\nAge: %d\n\n", head->name, head->age);
writeToFile(fptr, head->next);
}
else
fprintf(fptr, "\nPet Name: %s\nAge: %d\n\n", head->name, head->age);
}
Output(on console):
How many pets do you have? 3
Name of Pet: Tommy
Age of Pet: 3
Name of Pet: Julia
Age of Pet: 4
Name of Pet: Hedgehog
Age of Pet: 5
Name of Pet: Tommy
Age of Pet: 3
Name of Pet: Julia
Age of Pet: 4
Name of Pet: Hedgehog
Age of Pet: 5
Output(inside petname.txt file):
Pet Name: Tommy
Age: 3
Pet Name: Julia
Age: 4
Pet Name: Hedgehog
Age: 5

Linked List Appcrash

I was trying to do an example about linked list. First, I added the values to the variables and there was no problem. But when I tried to get values from user, the program crashed when entering midterm 2 grade. I tried other input functions but the result is same. Where is the problem?
#include <stdio.h>
struct student
{
char *name;
int m1,m2,final;
struct student* next;
};
main()
{
addStudent();
system("PAUSE");
}
addStudent()
{
struct student *node = NULL;
struct student *firstnode;
firstnode = (struct student *)malloc(sizeof(struct student));
node = firstnode;
printf("press 0 to exit \n");
while(1)
{
printf("Student name: ");
scanf("%s", node->name)
if(node->name == "0") break;
printf("Midterm 1: ");
scanf("%d", node->m1);
printf("Midterm 2: ");
scanf("%d", node->m2);
printf("Final: ");
scanf("%d", node->final);
node->next = (struct student *)malloc(sizeof(struct student));
node = node->next;
}
node->next = NULL;
node = firstnode;
while(node->next);
while(node->next != NULL)
{
printf("%s - ",node->name);
printf("%d ", node->m1);
printf("%d ", node->m2);
printf("%d ", node->final);
node = node->next;
}
system("PAUSE");
return 0;
}
Fix 1
Remove the line
while(node->next);
Reason: It will put you on an infinite loop in most cases and it is unnecessary.
Fix 2
Replace the loop
while(node->next != NULL) {
}
with
if (node->next != NULL) {
while (node->next->next != NULL) {
}
}
Reason: You are allocating one additional struct each time and keeping it empty for reading next time. So the Linked List will end before the next becomes NULL.
Fix 3
Replace following in struct
char *name;
with
char name[80];
Reason: Memory not being allocated.
Fix 4
Replace at all occurrences of scanf (except for name)
scanf("%d", node->m1);
with
scanf("%d", &node->m1);
Reason: scanf needs memory location of data to be read.
Good luck
Your code has multiple errors.
To start with, the first scanf("%s", node->name) is missing its terminating semicolon.
Next, your function signatures are sloppy. main() should be int main(void). addStudent() should be int addStudent(void). (Or, get rid of its return 0 and let it return void.) Since you don't pre-declare addStudent(), you should define it before main() so that main() can know about it.
The crash, though, is because you haven't allocated memory for node->name. You've allocated memory for a node, but that doesn't give you space to put the name.

How do I copy a value of array of strings to char array?

I am writing a program that will let user add or delete the car from inventory.Right now,
I am trying to get user to choose a car name instead of explicitly stating name and I created a struct CriteriaSelector in which array name companyList will store value of companies and when I let user choose car name it will copy a string from companyList at a particular index into the char array called carname which will then be copied into carname char array in the CarData object.
The thing is whenever I compile the below code, I get the error saying expected specifier qualifier list before 'companyList' at line 27 and I don't know what to do?
Can anybody help?
#include <stdio.h>
#include <stdlib.h>
#define MAX_WORD_LENGTH 20
typedef struct cardata{
char carname[MAX_WORD_LENGTH];
char carmodel[MAX_WORD_LENGTH];
char caryear[MAX_WORD_LENGTH];
char cartype[MAX_WORD_LENGTH];
int quantity;
}CarData;
struct node{
CarData data;
struct node *next;
struct node *prev;
}*start=NULL;
typedef struct criteriaselector{
const char *companyList[10];
companyList[0] = "Toyota"; <-- This is where error is happening!!(Line 27)
companyList[1] = "Honda";
companyList[2] = "Hyundai";
companyList[3] = "Nissan";
companyList[4] = "Mitsubishi";
companyList[5] = "Volksvagon";
companyList[6] = "Acura";
companyList[7] = "Ford";
companyList[8] = "Dodge"
companyList[9] = "GMC";
}CriteriaSelector;
void insert_first(){
struct node *ptr;
CriteriaSelector criteriaselector;
char carname[MAX_WORD_LENGTH];
char carmodel[MAX_WORD_LENGTH];
char caryear[MAX_WORD_LENGTH];
char cartype[MAX_WORD_LENGTH];
int carQuantity;
int ch;
printf("\nChoose your car");
printf("\n\n\n1.Toyota \n2.Honda \n3.Hyundai \n4.Nissan \n5. Mitsubishi \n6. Volksvagon \n7. Acura \n8. Ford \n9. Dodge \n10. GNC Exit\n");
scanf("%d", &ch);
strcpy(carname,criteriaselector.companyList[ch-1]);
printf("\n\nEnter the car model: ");
scanf("%s", carmodel);
printf("\n\nEnter the car year: ");
scanf("%s", caryear);
printf("\n\nEnter the car type: ");
scanf("%s", cartype);
printf("\n\nEnter the quantity of models: ");
scanf("%d", &carQuantity);
if(start==NULL){
start=(struct node *)malloc(sizeof(struct node));
strcpy(start->data.carname,carname);
strcpy(start->data.carmodel,carmodel);
strcpy(start->data.caryear,caryear);
strcpy(start->data.cartype,cartype);
start->data.quantity=carQuantity;
start->prev=NULL;
start->next=NULL;
}else{
ptr=start;
start=(struct node *)malloc(sizeof(struct node));
strcpy(start->data.carname,carname);
strcpy(start->data.carmodel,carmodel);
strcpy(start->data.caryear,caryear);
strcpy(start->data.cartype,cartype);
start->data.quantity=carQuantity;
start->next=ptr;
}
}
void delete_first(){
struct node *ptr;
char carname[MAX_WORD_LENGTH];
char carmodel[MAX_WORD_LENGTH];
char caryear[MAX_WORD_LENGTH];
char cartype[MAX_WORD_LENGTH];
char modelNumber[MAX_WORD_LENGTH];
int carQuantity;
if(start==NULL){
printf("\n\nLinked list is empty.\n");
}else{
ptr=start;
printf("\nThe car for which the entry is removed is %s \n",ptr->data.carname);
strcpy(start->data.carname,carname);
strcpy(start->data.carmodel,carmodel);
strcpy(start->data.caryear,caryear);
strcpy(start->data.cartype,cartype);
start->data.quantity=carQuantity;
start=start->next;
free(ptr);
}
}
void display()
{
struct node *ptr=start;
int i=1;
if(ptr == NULL){
printf("\nLinklist is empty.\n");
}else{
printf("\nSr. No Make Model Year Type Quantity\n");
while(ptr != NULL){
printf("\n%d.\t%s %s %s %s %d\n", i,ptr->data.carname,ptr->data.carmodel,ptr->data.caryear,ptr->data.cartype,ptr->data.quantity);
ptr = ptr->next;
i++;
}
}
}
int main(void)
{
int ch;
do
{
printf("\n\n\n1. Insert \n2. Delete \n3. Display \n4. Exit\n");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1:
insert_first();
break;
case 2:
delete_first();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("\n\nInvalid choice. Please try again. \n");
}
} while(1);
return EXIT_SUCCESS;
}
You can't mix definitions of a struct with initialisation.
typedef struct criteriaselector{
const char *companyList[10];
companyList[0] = "Toyota"; // This bit needs to be elsewhere.
Instead, after you declare an instance of the struct, you'll then need to fill in the values. For example:
typedef struct criteriaselector{
const char *companyList[10];
}
.....
void some_function() {
CriteriaSelector criteriaselector;
criteriaselector.companyList[0] = "Toyota"
.... etc
However, it looks like you were intending to make a constant, rather than describe a structure. Instead of the whole struct definition, you can do:
const char *criteriaselector[10] = {"Toyota", "Honda" ... }
somewhere in global scope. This will declare a "global" array of constant strings.
As an aside, there's a little subtlety with the way that const works here. This declaration says "define an array of pointers to constant chars". This means that you can't change the strings themselves, but you can change the pointers. So, you can't do:
criteriaselector[1][0] = '\0' // changing a character inside a const string
But, you can do:
criteriaselector[1] = "some other string".
This probably isn't what you meant. Instead, we can say "define an array of constant pointers to constant strings", like this:
const char * const criteriaselector[10] = {"Toyota", "Honda" ... }
That way, you won't be able to change the contents of the string, or which strings are pointed to.
The comments on that question that I linked explain this in a bit more detail.
You cannot initialize variables inside a structure. This is because a struct defines a type and not a variable. You can initialize a structure members outside the structure definition using a structure variable (criteriaselector in your case) and .or -> access specifiers.
For eg.,
criteriaselector.companyList[0] = "Ford";

Resources