C Programming segfault on scanf - c

I have written the following code segment and am having trouble understanding why it would not get to the last printf line. I get a segfault immediately after line 4. The kill_char is just used to kill the 'enter' character added in the previous scanf. Any help would be greatly appreciated, thanks!
int remove = 0;
char kill_char = 'a';
printf("Enter the product number to be removed: ");
scanf("%d", &remove);
scanf("%c", &kill_char);
printf("Does not get here");
EDIT:
Full code is as follows, with the error in the removeProduct function
#include <stdio.h>
#include <stdlib.h>
struct product_node {
char *supply_type;
long number;
char *description;
float price;
int quantity_bought;
float retail_price;
int quantity_sold;
struct product_node *next;
};
struct product_node *head;//declaring head out here
//allows the list to be in scope for the functions
/*Function Prototypes*/
void addProduct();
void removeProduct();
void listProduct();
void listSupplierTypes();
void supplierTypeProfit();
void totalProfit();
void addProduct(){
char kill_char = 'a';//used to kill the enter characters
struct product_node *new_node;
new_node = malloc(sizeof(struct product_node));
printf("\nEnter a string for type: ");
scanf( "%s", &(*new_node).supply_type);
scanf("%c", &kill_char);
printf("Enter the product number: ");
scanf("%ld", &(*new_node).number);
scanf("%c", &kill_char);
printf("Enter the description: ");
scanf("%s", &(*new_node).description);
scanf("%c", &kill_char);
printf("Enter the wholesale price: ");
scanf("%f", &(*new_node).price);
scanf("%c", &kill_char);
printf("Enter the quantity bought: ");
scanf("%d", &(*new_node).quantity_bought);
scanf("%c", &kill_char);
printf("Enter the retail price: ");
scanf("%f", &(*new_node).retail_price);
scanf("%c", &kill_char);
printf("Enter the quantity sold: ");
scanf("%d", &(*new_node).quantity_sold);
scanf("%c", &kill_char);
struct product_node *walker;
walker = head;
int can_insert = 1;
while (!(walker == NULL))
{
if (((*walker).number == (*new_node).number) && ((*walker).supply_type == (*new_node).supply_type))
{
can_insert = 0;
}
walker = (*walker).next;
}
if (can_insert==1)
{
(*new_node).next = head;
head = new_node;
printf("Insertion Successful");
}
else
{
printf("\nERROR INSERTING:This product name and number is already in the list\n");
}
free(new_node);
}
void removeProduct(){
int remove = 0;
char kill_char = 'a';
printf("Enter the product number to be removed: ");
scanf("%d", &remove);
scanf("%c", &kill_char);
printf("Does not get here");
struct product_node *walker;
struct product_node *prev;
prev = head;
walker = (*head).next;
if ((*prev).number == remove)
{
head = walker;
}//points head to second node to remove first
while (!(walker = NULL))
{
if ((*walker).number == remove)
{
(*prev).next = (*walker).next;
}
}
}
void listProduct(){
printf("Still unsure what defines a supplier...");
}
void listSupplierTypes(){
printf("Same as above");
}
void supplierTypeProfit(){
printf("Again");
}
void totalProfit(){
float total = 0.0;
struct product_node *walker;
walker = head;
while(!(walker == NULL))
{
total += ((float)(*walker).quantity_sold * (*walker).retail_price) - ((float)(*walker).quantity_bought * (*walker).price);
walker = (*walker).next;
}
printf("Total Profit is: $%.2f\n", total);
}
int main()
{
head = NULL;
char *temp_type;
char *temp_description;
int temp_number, temp_quantity_bought, temp_quantity_sold;
float temp_price, temp_retail_price;
while(!feof(stdin))
{
scanf( "%s %ld %s %f %d %f %d\n", &temp_type, &temp_number, &temp_description, &temp_price, &temp_quantity_bought, &temp_retail_price, &temp_quantity_sold);
struct product_node *new_node;
new_node = malloc(sizeof(struct product_node));
(*new_node).next = head;
head = new_node;
(*head).supply_type = temp_type;
(*head).number = temp_number;
(*head).description = temp_description;
(*head).price = temp_price;
(*head).quantity_bought = temp_quantity_bought;
(*head).retail_price = temp_retail_price;
(*head).quantity_sold = temp_quantity_sold;
}
freopen("/dev/tty", "rw", stdin);
int done=0;
int selection=0;
while (!done)
{
printf("\nMENU OPTIONS:\n");
printf("1. Add a product number\n");//Okay
printf("2. Remove a product number\n");
printf("3. List the products for a supplier\n");
printf("4. List all unique supplier types\n");
printf("5. Show profit margin for a specific supplier type\n");
printf("6. Show total profit\n");//Okay
printf("7. Quit\n");//Okay
printf("Enter a selection (1-7): ");
scanf("%d", &selection);
char garbage = 'a';
scanf("%c", &garbage);
switch(selection){
case 1:
addProduct();
break;
case 2:
removeProduct();
break;
case 3:
listProduct();
break;
case 4:
listSupplierTypes();
break;
case 5:
supplierTypeProfit();
break;
case 6:
totalProfit();
break;
case 7:
done = 1;
break;
default:
printf("Invalid selection.\n");
break;
}
}
}

remove is the name of a standard function, declared in <stdio.h>. Defining your own object or other entity with the same name has undefined behavior. The call may be trying to store an int value at the address of the remove() function.
Try picking a different name.
UPDATE: I think I was mistaken. Function names defined in standard headers are reserved for use as identifiers with external linkage; they're also reserved for use as a macro name and as an identifier with file scope if the relevant header is #included. Neither should apply in your case. It's still a good idea to avoid defining such identifiers yourself, though.
Also, this probably isn't related to the symptom you're seeing, but
scanf("%d", &obj);
has undefined behavior if the input is a syntactically valid integer whose value is outside the range of int.
Execution does reach your "Does not get here" line. You're not seeing it because the buffered output isn't printed before the program dies. Change this:
printf("Does not get here");
to this:
printf("Does not get here\n");
fflush(stdout);
When I run your program under gdb, I see the seg fault at:
if ((*walker).number == remove)
I also get several warnings during compilation:
c.c: In function ‘addProduct’:
c.c:32:5: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’ [-Wformat]
c.c:38:5: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’ [-Wformat]
c.c: In function ‘main’:
c.c:134:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’ [-Wformat]
c.c:134:9: warning: format ‘%ld’ expects argument of type ‘long int *’, but argument 3 has type ‘int *’ [-Wformat]
c.c:134:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 4 has type ‘char **’ [-Wformat]
which could easily cause memory corruption. Fix those and see what happens.
UPDATE 2:
I don't know what other programs your code may still have, but this:
while (!(walker = NULL))
{
if ((*walker).number == remove)
{
(*prev).next = (*walker).next;
}
}
is almost certainly wrong. You're using an assignment = operator where you probably want an equality comparison ==. And after fixing that, the code would be clearer as follows:
while (walker != NULL)
{
if (walker->number == remove)
{
prev->next = walker->next;
}
}
That's just what jumped out at me when I took a very quick look after gdb told me the segfault was on the line if ((*walker).number == remove).
Try using a debugger yourself, fix one problem at a time, and pay attention to any compiler warnings.

Your printf does not appear because it didn't flush from the buffer, just use a "\n" at the end of the string and you will see it:
printf("Does not get here\n");
And so, the error, is not at scanf, but at this line:
walker = (*head).next;
As I could see, the program may reach there while head is not allocated, so you can check it at the beginning of the function:
void removeProduct(){
int remove = 0;
char kill_char = 'a';
if (head == NULL) {
printf("No product to remove!\n");
return;
}
I'm not sure if there is any other errors, but this is the one I noticed.
BTW, you can avoid using kill_char by inserting a space at the beginning and end of format string on scanf:
scanf(" %d ", &remove);
It will skip all white characters (as tabs, spaces and line breakers). And, if you really just want to skip one, and only one, character, you can use * to ignore the match:
scanf("%d%*c", &remove);

Related

format specifies type 'int *' but the argument has type 'int' [-Wformat] in C language when typing scanf("%d", (*(pArr[i])).age);

I have a program where I have to add a name, age and 2 courses for a student in a database using pointer structures and pointer arrays in C. I am able to store the name entered by the user into the database but not the age. When I enter age, this error shows up "format specifies type 'int ' but the argument has type 'int' [-Wformat]
scanf("%d", ((pArr[i])).age);"
I know that this could be a common error but I am a bit new to C. Any help would be appreciated.
My function for entering new values looks like:-
Also, this code is still in development, so please point me out any extra errors if there are :)
//global
#define SIZE 30
#define fieldLength 200
struct db_type
{
char name[fieldLength];
int age;
char course1[fieldLength];
char course2[fieldLength];
char status[fieldLength];
};
struct courseInfo
{
char code [20]; // e.g., EECS2030
char title [fieldLength];
char date [20];
char time_start [20];
char time_end [20];
char location [20];
};
struct courseInfo courseArr[SIZE];
int main(int argc, char *argv[])
{
struct db_type * db_pArr[SIZE]; // main db storage
init_list(db_pArr); // set to NULL
init_courseArr(); // load course from diskfile
char choice;
for(; ;){
choice = prompt_menu();
switch (choice)
{
case 'n': enterNew(db_pArr); break;
case 'q': exit(1); // terminate the whole program
}
}
return 0;
}
void enterNew(struct db_type * pArr[SIZE]){
static int i=0;
static int j=0;
int flag = 0;
pArr[i] = malloc(sizeof(struct db_type));
printf("name: ");
scanf("%s", (*pArr[i]).name);
printf("age: ");
scanf("%d", (*(pArr[i])).age); //error here
printf("course-1: ");
scanf("%s", (*pArr[i]).course1);
while(flag == 0)
for(int j=0; j<SIZE; j++){
if(strcmp((*pArr[i]).course1, courseArr[j].code) == 1 && flag == 0){
printf("course does not exist, enter again: \n");
printf("course-1: ");
scanf("%s", (*pArr[i]).course1);
}
else
flag = 1;
}
if(flag == 1)
++i;
// further code in development
// printf("course-2: ");
// scanf("%s", pArr[i].course2);
}
Further extra information about what program does
-> This program basically is a part of a student database management system. When user enters 'n' or 'N', this function is invoked. User has the option to enter student name, age, student's course-1 and course-2. It also has to check whether course-1 and course-2's start time and end time clash or not and store it in a variable called char status[] of structure db_type.
Change
scanf("%d", (*(pArr[i])).age);
to
scanf("%d", &(*(pArr[i])).age);
scanf() requires a pointer to the variable and adding & in front of it returns the pointer of the variable.

The following C code shows that : format '%d' expects argument of type 'int *', but argument 7 has type float *

The following code shows that : format '%d' expects argument of type 'int *', but argument 7 has type float *. I'm not an expert but I can't distinguish the error. This issue is present at the scanf. Along with this issue there are 3 more related warnings. It's at line 158 in the void edit () section. I keep trying and getting this very same thing. I ask if someone can please kindly assist?
Problem:
if(strcmp(e.name,empname) == 0)
{
printf("\nEnter new name,sex,address,designation,age,salary,employee ID ");
scanf("%s %s %s %s %d %.2f %d",e.name,e.sex,e.adrs,e.dsgn,&e.age,&e.slry,&e.empID);
fseek(fptr,-recsize,SEEK_CUR);
fwrite(&e,recsize,1,fptr);
break;
}
Struct here:
struct employee
{
char name[50];
char sex;
char adrs[50];
char dsgn[25];
int age,empID;
float slry;
};
Entire code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <ctype.h>
#include <stdbool.h>
#include <windows.h>
#include "struct.h"
void insert();
void list();
void edit();
void del();
void ext();
FILE * fptr, *ftemp;
struct employee e;
long int recsize;
char empname[50];
int main()
{
//FILE * fptr, *ft;
int choice;
//fptr = fopen("ems.txt","rb+");
fptr = fopen("ems.txt", "r+");
if (fptr == NULL)
{
printf("Can't find file! Attempting to create file... \n");
fptr = fopen("ems.txt","w+");
if(fptr == NULL)
{
printf("Can't create file. Exiting...");
ext(1);
}
}
//Explain the reason for this?
//recsize = (long int) sizeof(e);//
while(1)
{
printf("*******************************\n");
printf("\nEmployee management system");
printf("\n1. Insert employee information");
printf("\n2. List all employee information");
printf("\n3. Edit employee information");
printf("\n4. Delete employee information");
printf("\n5. Exit");
printf("\n\n*****************************\n");
printf("\n\n Enter your choice: ");
scanf("%d", &choice);
fflush(stdin);
switch(choice)
{
case 1:
puts("Insert was chosen");
insert();
break;
case 2:
puts("List was chosen");
list();
break;
case 3:
puts("Edit was chosen");
edit();
break;
case 4:
puts("Delete was chosen");
del();
break;
case 5:
puts("Exit was chosen");
ext(1);
break;
default:
puts("Choice is incorrect!!");
continue;
}
}
return 0;
}
void insert()
{
char next;
do
{
printf("********************************************************** \n");
printf("\nEnter the name of the employee: ");
fgets(e.name);
printf("\nEnter the sex of the employee (M/m or F/f): ");
fgets(&e.sex);
printf("\nEnter the address of the employee: ");
fgets(e.adrs);
printf("\nEnter designation of the employee: ");
fgets(e.dsgn);
printf("\nEnter age of the employee: ");
scanf("%d", &e.age);
printf("\nEnter basic salary of the employee: ");
scanf("%f", &e.slry);
printf("\nEnter the employee's ID: ");
scanf("%d", &e.empID);
fputs(e.name, fptr);
fputs(&e.sex, fptr);
fputs(e.adrs, fptr);
fputs(e.dsgn, fptr);
fprintf(fptr, "%d \n%f \n%d \n", e.age, e.slry, e.empID);
// fwrite(&e,recsize,1,fptr);
fflush(stdin);
printf("\nDo you want to input more? (y/n): ");
next = getche();
printf("\n");
}
while(next !='n');
fclose(fptr);
}
void list ()
{
/* what is going on here??? */
while(fread(&e,recsize,1,fptr)==1)
{
printf("\n%s %c %s %s %d %.2f %d",e.name,e.sex,e.adrs,e.dsgn,e.age,e.slry,e.empID);
}
getche();
return ;
}
void edit ()
{
char next;
do
{
printf("Enter the employee name to be edited: ");
scanf("%s", empname);
while(fread(&e,recsize,1,fptr)==1)
{
if(strcmp(e.name,empname) == 0)
{
printf("\nEnter new name,sex,address,designation,age,salary,employee ID ");
scanf("%s %s %s %s %d %.2f %d",e.name,e.sex,e.adrs,e.dsgn,&e.age,&e.slry,&e.empID);
fseek(fptr,-recsize,SEEK_CUR);
fwrite(&e,recsize,1,fptr);
break;
}
}
printf("\nEdit another record(y/n)");
next = getche();
fflush(stdin);
}
while(next != 'n');
return ;
}
void del()
{
char next;
do
{
printf("\nEnter name of employee to delete: ");
scanf("%s",empname);
ftemp = fopen("Temp.dat","wb");
while(fread(&e,recsize,1,fptr) == 1)
{
if(strcmp(e.name,empname) != 0)
{
fwrite(&e,recsize,1,ftemp);
}
}
fclose(fptr);
fclose(ftemp);
remove("ems.txt");
rename("Temp.dat","ems.txt");
fptr = fopen("ems.txt", "rb+");
printf("Delete another record(y/n)");
fflush(stdin);
next = getche();
}while(next !='n');
}
It would have been good if you showed us all the errors you got on that line:
x1.c: In function ‘edit’:
x1.c:170:17: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
scanf("%s %s %s %s %d %.2f %d",e.name,e.sex,e.adrs,e.dsgn,&e.age,&e.slry,&e.empID);
^
x1.c:170:17: warning: unknown conversion type character ‘.’ in format [-Wformat=]
x1.c:170:17: warning: format ‘%d’ expects argument of type ‘int *’, but argument 7 has type ‘float *’ [-Wformat=]
x1.c:170:17: warning: too many arguments for format [-Wformat-extra-args]
The first warning goes back to your prior question. e.sex has type char (which gets promoted to int) but you specified %s which expects a char *. To read this field, you want to use the %c format specifier which reads a single character instead of a sequence of characters, and you want to pass the address of the field you want to read into, i.e. &e.sex.
The second warning is due to your use of %.2f as a format specifier. Unlike printf, scanf doesn't take a precision. Change this to %f. Once you do that, the third error goes away.
As a rule, always address compilers errors from top to bottom, as problems earlier in the code can cascade down.

why do is says "[Warning] passing argument 1 of 'gets' from incompatible pointer type"?

[Warning] passing argument 1 of 'gets' from incompatible pointer type
I want to create a program that allows me to input the student full name that's why I used the function "gets" however when I run my program it will only read the input on name, age and telephone it won't read the address why is this happening ? can someone help me? I still new to this programming thing
#include<stdio.h>
#include<string.h>
#include<conio.h>
struct data
{
char name[10][40];
int age[10];
char address[10][40];
char telephone[10][40];
}d;
main()
{
char ans='y';
int i;
i=1;
while(ans=='y'||ans=='Y')
{
printf("Enter name: ");
gets(d.name[i]); //this is the warning goes
printf("Enter age: ");
scanf("%d",&d.age);
printf("Enter address: ");
gets(d.address[i]); //this is where the warning goes
printf("telephone: ");
scanf("%s",&d.telephone[i]);//this is where the warning goes
i++;
printf("Enter another [Y/N]? ");
scanf("%c",&ans);
}
getch();
}

Calculating Average from array and seperate structure

Trying to make a program that prints data entered into a file.
Everything is working all and good apart from the Calculating Average for marks entered.
I can't seem to figure out how to do it, even though it should be simple I just cant get my head around it.
The error I am currently getting is:
"temp->mark = temp->mark + studentArray[j];" (Invlalid operands to
binary + (have 'float' and 'char *').
Much appreciated if someone could help me. I have tried the following
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
struct student{
char name[30];
int id;
float mark;
};
int count = 0;
void student_update(char *stuadd);
void display(char *stuadd);
void main(int argc, char *studentArray[100])
{
int choice;
while(1)
{
printf("Welcome to Student Archives\n\n");
printf("1. Display Students' Details\n");
printf("2. Calculate average of all students’ marks \n");
printf("3. Add new student to the record \n");
printf("4. Quit Program\n");
scanf("%d",&choice);
switch(choice)
{
case 1:display(studentArray[100]);
break;
case 2:
break;
case 3:
student_update(studentArray[100]);
break;
case 4: printf("Program Terminated.\n");
exit(0);
default: printf("Wrong Choice. Enter again\n");
break;
}
}
}
void display(char *stuadd)
{
FILE *fptr;
char ch;
int rec = count;
fptr = fopen("stuadd.txt", "r");
struct student *temp = (struct student *)malloc(sizeof(struct student));
if (fptr == NULL)
printf("File does not exist.");
else
{
while (rec)
{
fread(temp->name, 50, 1, fptr);
printf(" %s\n", temp->name);
fread(&temp->id, sizeof(int), 1, fptr);
printf("%d", temp->id);
fread(&temp->mark, sizeof(int), 1, fptr);
printf("%.2f", temp->mark);
rec--;
}
}
fclose(fptr);
free(temp);
free(temp->name);
}
void calculateAverage(char *studentArray[100])
{
struct student *temp = (struct student *)malloc(sizeof(struct student));
int j;
float avg;
temp->mark = avg = 0;
for(j = 0; j < 100; j++)
{
temp->mark = temp->mark + studentArray[j];
}
avg = (float)temp->mark / j;
printf("Average of students' total marks are: %.2f",avg);
}
void student_update(char *stuadd)
{
FILE *fptr;
fptr = fopen("stuadd.txt", "a+");
struct student *temp = (struct student *)malloc(sizeof(struct student));
if (fptr == NULL)
printf("\nError.");
else
{
printf("\nEnter the students' name\n");
scanf(" %[^\n]s", temp->name);
printf("Enter the students' ID\n");
scanf("%d", &temp->id);
printf("Enter the students' mark\n");
scanf("%f", &temp->mark);
fprintf(fptr, "%s %d %.2f", temp->name, temp->id, temp->mark);
count++;
}
fclose(fptr);
free(temp);
free(temp->name);
}
The posted code does not compile!
under ubuntu linux, using:
gcc -ggdb -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c "untitled.c" (in directory: /home/richard/Documents/forum)
the compiler outputs the following:
untitled.c:16:6: warning: return type of ‘main’ is not ‘int’ [-Wmain]
void main(int argc, char *studentArray[100])
^~~~
untitled.c: In function ‘main’:
untitled.c:16:15: warning: unused parameter ‘argc’ [-Wunused-parameter]
void main(int argc, char *studentArray[100])
^~~~
untitled.c: In function ‘display’:
untitled.c:48:10: warning: unused variable ‘ch’ [-Wunused-variable]
char ch;
^~
untitled.c:45:20: warning: unused parameter ‘stuadd’ [-Wunused-parameter]
void display(char *stuadd)
^~~~~~
untitled.c: In function ‘calculateAverage’:
untitled.c:83:33: error: invalid operands to binary + (have ‘float’ and ‘char *’)
temp->mark = temp->mark + studentArray[j];
~~~~~~~~~~ ^ ~~~~~~~~~~~~~~~
untitled.c:86:29: warning: conversion to ‘float’ from ‘int’ may alter its value [-Wconversion]
avg = (float)temp->mark / j;
^
untitled.c: In function ‘student_update’:
untitled.c:91:27: warning: unused parameter ‘stuadd’ [-Wunused-parameter]
void student_update(char *stuadd)
^~~~~~
Compilation failed.
There are some other problems, like:
free(temp);
free(temp->name);
That is accessing a pointer into allocated memory after the allocated memory has been passed to free() The result is indefined behavior. Suggest:
free(temp->name);
free(temp);
Regarding the following statements
FILE *fptr;
fptr = fopen("stuadd.txt", "a+");
struct student *temp = (struct student *)malloc(sizeof(struct student));
if (fptr == NULL)
printf("\nError.");
Always check for an error indication immediately after the call to the C library function.
output error messages to stderr, not stdout
When the error indication is from a C library function, then immediately call perror(); to output both your error message AND the text reason the system thinks the error occurred, all to stderr
when calling any of the heap allocation functions: malloc calloc realloc, 1) the returned type is void* which can be assigned to any pointer. Casting just clutters the code, making it more difficult to understand, debug, etc. 2) always check (!=NULL) the returned value to assure the operation was successful. Suggest:
FILE *fptr;
fptr = fopen("stuadd.txt", "a+");
if ( !fptr )
{
perror("fopen failed");
exit( EXIT_FAILURE );
}
// implied else, fopen successful
struct student *temp = malloc(sizeof(struct student));
if( !temp )
{
perror( "malloc failed" );
exit( EXIT_FAILURE );
}
// implied else, malloc successful
regarding:
scanf(" %[^\n]s", temp->name);
That call to scanf() is nonsense. Since the input format specifier %[^\n] will stop input from stdin when it encounters a newline sequence, there is no possible way for the next char in stdin to be a s When calling any of the scanf() family of functions, always check the returned value to assure the operation was successful. when using the input format specifiers %s and/or %[...] always include a MAX CHARACTERS modifier that is one less than the length of the input buffer to avoid any possibility of buffer overflow (and the resulting undefined behavior). Suggest removing the trailing s in the format string and check the return value and limiting the total number of characters that can be input, as in:
if( scanf(" %29[^\n]", temp->name) != 1 )
{
fprintf( stderr, "scanf failed to input the student name\n" );
exit( EXIT_FAILURE );
}
regarding:
for(j = 0; j < 100; j++)
{
temp->mark = temp->mark + studentArray[j];
}
there is no array studentArray[] so this will never produce the desired results.
regarding the error message:
avg = (float)temp->mark / j;
untitled.c:83:33: error: invalid operands to binary + (have ‘float’ and ‘char *’)
temp->mark = temp->mark + studentArray[j];
of course a 'float` value cannot be added to a pointer to a char array. What were you actually trying to accomplish?
All the above is just the 'tip of the iceburg' of problems in the posted code. Suggest using a debugger and stepping through your code to determine the many problems

Need to make a function that deletes info about last student in the list

I need to make a function that will delete the info about the last student, and it returns 1 if it is successful or 0 if not.
I'm stuck here, should I use pointers or something, I'm really lost here.
Here is the code:
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef struct _students
{
int index;
char name[20];
} students;
int main() {
int n;
printf("How much students you want: ");
scanf("%d" ,&n);
int i=0;
struct _students list[n];
for(i;i<n;i++)
{
printf("Type info about student nbr. %d \n" ,i+1);
printf("\n");
printf("index: ");
scanf("%d", &list[i].index);
printf("name: ");
scanf("%s", &list[i].name);
printf("\n");
}
printf("---------------");
int j=0;
for(j;j<n;j++)
{
printf("Info about student: %d \n", j+1);
printf("\n");
printf("Index: %d \n",list[j].index);
printf("Name: %s \n" ,list[j].name);
printf("\n");
}
return 0;
}
Thanks
I would use a comment, but i get a message that i need 50 reputation to make a comment.
printf is part of stdio.h so if you use it, you need to include it.
iostream is not a C library as stated in the comments.
When i ran your code quickly, i got this error.
test.c:39:15: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat=]
scanf("%s", &list[i].name);
You have to remember that an array is treated like a pointer. so when you s[], you do not need the & in front of s in scanf. s is treaded as a pointer to the first element of the array.
scanf("%s", list[i].name);
Once i removed the & and removed iostream and added stdio.h your code compiled.

Resources