Initialization from incompatible pointer type warning - c

I am trying to make an array of pointer pointers to point in an stuct.
until now I have the following code done
#include <stdlib.h>
typedef struct ID{
char firstName[21];
char lastName[21];
char phoneNumber[11];
}ID;
int main(int argc, char *argv[]) {
int answere,i=0;
printf("******* WELCOME TO PHONEBOOK **********\n\n\n");
printf("***************************************\n");
printf("* MENU *\n");
printf("* *\n");
printf("* 1.Add New 2.Print list 3.Exit *\n\n");
printf("***************************************\n\n");
ID* ptr=(int*)malloc(21*sizeof(ID));
do
{
printf("Please select (1, 2 or 3): ");
scanf("%d",&answere);
if(answere!=1 && answere!=2 && answere!=3)
{
printf("//...Error...\\ please give me a correct answere: ");
}
if(answere == 1)
{
i++;
addNew(&ptr,i);
}
else if(answere==2)
{
PrintList(&ptr,i);
}
}while(answere!=3);
return 0;
}
so the ptr array gonna be each time a new user and I want it to max out at 3 users the code for adding a new user is the following
ID addNew(ID *ptr,int i){
char fname,lname,phone;
if(i<3)
{
int l;
for (l=1;l<=3;l++)
{
ID user;
ptr[l] = user;
printf("enter the first name: ");
scanf("%s",&fname);
*ptr->firstName= fname;
printf("enter the last name: ");
scanf("%s",&lname);
*ptr->lastName = lname;
printf("enter the phone number: ");
scanf("%s",&phone);
*ptr->phoneNumber = phone;
}
}
else
{
printf("sorry but you have reach max capacity\n");
}
}
the problem is that when I am calling the first fuction after the assignment of values the programm crashes. What is wrong?

You function prototype ID addNew(ID *ptr,int i), so you must call it with addNew(ptr,i), not using &ptr because you've already declared ptr as ID*.
I hope it helps.

you scan a string into a single character. which probably results in memory overrung and thus the behavior of your program is UNDEFINED
scanf("%s",&fname); // here fname is only 1 char long, probably a mistake

Related

how do I print the stuct members using an array pointers?

The code I have wrote so far is the following without the libraries. Basically I used the stdio.h and the stdlib.h.
typedef struct ID{
char firstName[21];
char lastName[21];
char phoneNumber[11];
}ID;
ID PrintList(ID *ptr,int i){
int l=1;
printf(" # First Name Last Name Phone Number\n");
while(l<i+1)
{
printf(" %d. %s",l,&ptr[l]);
l++;
}
}
ID addNew(ID *ptr,int i){
char fname[21],lname[21],phone[11];
if(i<3)
{
ID user;
ptr[i] = user;
printf("enter the first name: ");
scanf("%s",&fname);
*ptr->firstName= fname;
printf("enter the last name: ");
scanf("%s",&lname);
*ptr->lastName = lname;
printf("enter the phone number: ");
scanf("%s",&phone);
*ptr->phoneNumber = phone;
}
else
{
printf("sorry but you have reach max capacity\n");
}
}
int main(int argc, char *argv[]) {
int answere,i=0;
printf("******* WELCOME TO PHONEBOOK **********\n\n\n");
printf("***************************************\n");
printf("* MENU *\n");
printf("* *\n");
printf("* 1.Add New 2.Print list 3.Exit *\n\n");
printf("***************************************\n\n");
ID* ptr=(int*)malloc(21*sizeof(ID));
do
{
printf("Please select (1, 2 or 3): ");
scanf("%d",&answere);
if(answere!=1 && answere!=2 && answere!=3)
{
printf("...Error... \ngive me a correct answere\n");
}
if(answere == 1)
{
i++;
addNew(ptr,i);
}
else if(answere==2)
{
PrintList(ptr,i);
}
}while(answere!=3);
return 0;
}
So as I said my problem is that I am not able to print the members of the struct as I need to print them using the array of pointers though. I think that I just haven't written something right like it is just a little logic mistake in printf.
The only obstacle that I have is that the array of pointers is needed to be made in main.
You seem completely lost...
Some Basics
You are passing pointer/reference to first item of an array (address of the first item)
to get value at that address (dereference it) you can do two things:
*ptr //but I don't recommend using it with structures
ptr[0]
since you are using structures that are generally big you are expected to work with pointers and for that reason so called "arrow" operator exists which can be used to access members of structure pointer
ptr->firstName
So your function would look like this:
void PrintList(ID *ptr, int l)
{
int i;
printf(" # First Name Last Name Phone Number\n");
for(i = 0; i < l; i++)
{
printf("%2d. %s %s %s\n",
i, ptr[i].firstName, ptr[i].firstName, ptr[i].phoneNumber);
}
}
Also I recommend using '\t' instead of spaces to align the columns.

Insert structure arrays dynamic in C. Exited, segmentation fault

I have a problem with structure arrays, to insert dynamic values.
Cannot insert values ​​into dynamic arrays, response "Exited, segmentation fault".
Can anyone help me, that's problem.
Thank you
............................................................................................................................................................................................................................................................................................................................
Syntax:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#define FLUSH while (getchar() != '\n')
typedef struct{
char *Name;
int Qty;
} Item;
static void insert(Item* i, char *name, int qty)
{
i->Name = name;
i->Qty = qty;
}
int main() {
int storage = 0, menu;
printf("Temporary Storage\n");
//Input storage amount
bool isInputStorage = true;
while (isInputStorage) {
printf("Input Storage amount [1..10]: ");
scanf("%d", &storage);
if (storage <= 10 && storage >= 1) {
isInputStorage = false;
}
else {
printf("\n[!]Please enter numbers [1..10] for Storage amount.\n\n");
}
FLUSH;
}
Item *dataItems;
//Input Menu
bool isInputMenu = true;
while (isInputMenu) {
printf("\n\nMenu\n");
printf("=============\n");
printf("1. Add items\n");
printf("4. Exit\n");
printf("Choose Menu [1..4]: ");
scanf("%d", &menu);
if (menu >= 1 && menu <= 4) {
if (menu == 1) {
char* name;
int qty;
//Insert to arrays storage
int currentStorageAmount = sizeof(dataItems) / sizeof(dataItems[0]);
if (currentStorageAmount >= storage) {
printf("Storage is Full");
}
else {
printf("Input name of Item : ");
scanf("%s", name);
bool isQty = true;
while (isQty) {
FLUSH;
printf("Input qty of Item : ");
int correctQty = scanf("%d", &qty);
if (correctQty == 1) {
isQty = false;
}
else {
printf("\n[!]Please enter number for Qty!\n\n");
}
}
//action to insert
insert(&dataItems[currentStorageAmount], name, qty);
}
}
else if (menu == 4) {
printf("\nThank you for using this application.\n");
isInputMenu = false;
}
}
else {
printf("\n[!]Please enter numbers [1..4] for choose Menu.");
}
menu = 0;
FLUSH;
}
system("pause");
return 0;
}
Result:
Temporary Storage
Input Storage amount [1..10]: 4
Menu
=============
1. Add items
4. Exit
Choose Menu [1..4]: 1
Input name of Item : test
Input qty of Item : 5
exited, segmentation fault
You are asking about arrays but there is no one array in your code...
What you really have is the pointer to Item. This means three things:
You have not initialized this pointer, and it points to somewhere. So the expression &dataItems[currentStorageAmount] gives you a random position in memory that leads you to the segmentation fault.
The expression sizeof(dataItems) / sizeof(dataItems[0]) gives you something different from what you expect: size of the pointer divided to size of the structure. In other words it is zero.
You need to allocate memory before using the dataItems.
I check the code with GDB, the error is at line 65,
scanf("%s", name);
you have declared a pointer char* name, but you have not allocated its heap memory yet. The correct solution is to change the line,
char *name
To
char* name = malloc(128);
Then, the code is running.

Trying to print a struct element but getting blank. - C

I have a struct person that has the following elements, defined in data.h
typedef struct person{
char firstName[20];
char familyName[20];
char telephoneNum[20];
int type; // 0 = student / 1 = employee;
}newPerson;
I created an array of person[MAX_PERSONS] that is initialized in my menu() function. I then have an addFirstName(newPerson pers) function. However when I try to test print format using my printFormat(newPerson pers)function, I get blank, instead of the inputted name.
I have included the menu(), addFirstname(newPerson pers), and printFormat(newPerson pers) function below. I was wondering if anyone could tell me the reason for this. Any help or pointers would be appreciated. Thank you in advance.
int menu(){
int num = 0;
newPerson person[MAX_PERSONS];
int option; // for user input for menu
printf("\n\tPlease choose one of the following options to continue (0-9): ");
scanf("%d", &option );
printf("\n\tYou selected %d\n", option);
if (option == 0){ //program will close
printf("\tProgram will now close.\n");
exit(1);
}
if (option == 1){ //program will ask for name input
addRecord(person[num]);
printFormat(person[num]);
char choice[0];
printf("\n\t\tWould you like to enter another record? (y/n): ");
scanf("%s", choice);
if (choice[0] == 'y'){
num++;
addRecord(person[num]);
}
if (choice[0] == 'n'){
num++;
mainMenu();
}
/*
IF YES, THEN NUM++
THEN RUN ADDRECORD(PERSONNUM) AGAIN.
IF NO, THEN RETURN TO MAIN MENU.
PRINTMENU
THEN RUN MENU AGAIN
*/
}
printf("\n\tNot a valid option, please try again // THE END OF MENU FUNCTION\n");
return 0;
}
void addFirstName(newPerson pers){
char firstName[20];
printf("\n\tEnter first Name: ");
scanf("%20s", firstName);
strcpy(pers.firstName, firstName);
printf("\n\tThe name entered is %s", pers.firstName);
}
void printFormat(newPerson pers){
printf("\t\tThe name is %s", pers.firstName);
}
It's because you pass the structure to addFirstName by value meaning that the function receives a copy of the structure. And changing a copy will of course not change the original.
While C does not support passing arguments by reference, it can be emulated using pointers. So change the addFirstName function to receive a pointer to the structure as its argument.
Your big problem is that you are passing structures by value instead of by pointers. This result in that you change copies of original objects inside your function addFirstName and not the original object. You should declare it as:
void addFirstName( newPerson* pers);
void printFormat( newPerson* pers);
Example:
#include <stdio.h>
void call_by_value(int x) {
printf("Inside call_by_value x = %d before adding 10.\n", x);
x += 10;
printf("Inside call_by_value x = %d after adding 10.\n", x);
}
int main() {
int a=10;
printf("a = %d before function call_by_value.\n", a);
call_by_value(a);
printf("a = %d after function call_by_value.\n", a);
return 0;
}
this will produce:
a = 10 before function call_by_value.
Inside call_by_value x = 10 before adding 10.
Inside call_by_value x = 20 after adding 10.
a = 10 after function call_by_value.

Taking in unique inputs in a struct array in C

I am writing a program to create a structure named 'student'. I need to input various data about a particular student. Here is my program till now.
#include<stdio.h>
#include<stdlib.h>
struct student
{
char* name;
int id;
float marks_1;
float marks_2;
};
void main()
{
int num, var_i, var_j, var_k, var_l, duplicated_id = 0;
printf("Enter number of students\n");
scanf("%d", &num);
struct student s[num];
printf("Enter the data for the students\n");
for (var_i = 0; var_i < num; var_i++)
{
var_j = var_i + 1;
printf("Enter name of student_%d\n", var_j);
scanf(" %[^\n]%*c", &s[var_i].name);
printf("Enter id of student_%d\n", var_j);
scanf("%d", &s[var_i].id);
for (var_k = 0; var_k < var_i; var_k++)
{
if (s[var_k].id == s[var_i].id)
{
printf("Duplicate Id, program will exit");
return;
}
}
printf("Enter marks(sub_1) of student_%d\n", var_j);
scanf("%d", &s[var_i].marks_1);
printf("Enter marks(sub_2) of student_%d\n", var_j);
scanf("%d", &s[var_i].marks_2);
}
}
In the following for loop I am checking all the previously entered 'id' values to check if there is a duplicate. In case of a duplicate, the program will exit.
for(var_k=0;var_k<var_i;var_k++)
{
if(s[var_k].id==s[var_i].id)
{
printf("Duplicate Id, program will exit");
return;
}
}
Now instead of exiting the program I want to prompt the user to enter a different value. This goes on till he enters a unique value. How should I do it?
Any help appreciated.
This is wrong:
scanf(" %[^\n]%*c", &s[var_i].name);
You're passing the address of the pointer member name (i.e. you're passing a char **) to scanf() which per the format string, is expecting a char* and enough memory to hold the data it subsequently reads. This is invalid, is undefined behavior, and blindly overwrites data in the s[] array. Frankly I'm amazed this doesn't seg-fault your process.
Change this:
struct student
{
char* name;
int id;
float marks_1;
float marks_2;
};
To this:
struct student
{
char name[128]; // or some other suitable size.
int id;
float marks_1;
float marks_2;
};
And change this:
scanf(" %[^\n]%*c", &s[var_i].name);
To this:
scanf(" %[^\n]%*c", s[var_i].name);
I strongly suggest a size-limiter on that scanf() call as well, but I leave that to you to discover. Read about the API here.
Just use a loop.
here is some psudocode
bool isDuplicate = false
do
{
GetInput()
isDuplicate = CheckForDuplicate()
}while(isDuplicate);

How to approach and optimize code in C

I am new to C and very much interested in knowing how to approach any problem which has more than 3 or 4 functions, I always look at the output required and manipulate my code calling functions inside other functions and getting the required output.
Below is my logic for finding a students record through his Id first & then Username.
This code according to my professor has an excessive logic and is lacking in many ways, if someone could assist me in how should I approach any problem in C or in any other language it would be of great help for me as a beginner and yes I do write pseudo code first.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
int id; //Assuming student id to be unique
int age;
char *userName; //Assuming student userName to be unique
char *dept;
}student; // Alias "student" created for struct
student* createstruct(); // All function prototype declared
student* createArray();
void addstruct(student* s2);
void searchChar(student* s2,int num);
void searchInt(student* s2,int num);
student* createstruct() // function createStruct() to malloc data of struct student.
{
student *s;
s = (student*)malloc(sizeof(student));
s->userName = (char*)malloc(sizeof(char)*32);
s->dept = (char*)malloc(sizeof(char)*32);
printf("please enter id ");
scanf("%d",&s->id);
printf("please enter age ");
scanf("%d",&s->age);
printf("please enter userName ");
scanf("%31s",s->userName);
printf("please enter department ");
scanf("%31s",s->dept);
printf("\n");
return s;
}
student* createArray()
{
student *arr; //declaration of arr poiter, type struct student
arr = (student*)malloc(sizeof(student)*10); // memory allocated for a size of 10
return arr;
}
void addstruct(student *s2) // function for adding data to the structures in array
{
int i,num;
student* s1;
printf("please enter the number of records to add:");
scanf("%d",&num);
printf("\n");
if(num>0 && num<11)
{
for(i=0;i<num;i++) // if user want to enter 5 records loop will only run 5 times
{
s1 = createstruct();
s2[i].id = s1->id; // traversing each element of array and filling in struct data
s2[i].age = s1->age;
s2[i].userName = s1->userName;
s2[i].dept= s1->dept;
}
}
else if(num>10) // if user enters more than 10
{
for(i=0;i<10;i++) // loop will still run only 10 times
{
s1 = createstruct();
s2[i].id = s1->id;
s2[i].age = s1->age;
s2[i].userName = s1->userName;
s2[i].dept = s1->dept;
}
printf("Array is full"); // Array is full after taking 10 records
printf("\n");
}
searchInt(s2,num); // Calling searchInt() function to search for an integer in records
searchChar(s2,num); // Calling searchChar() function to search for a string in records
free(s1);
free(s2);
}
void searchChar(student* s2,int num) // function for searching a string in records of structure
{
char *c;
int i;
c = (char*)malloc(sizeof(char)*32);
printf("please enter userName to search ");
scanf("%31s",c);
printf("\n");
for (i=0;i<num;i++) //num is the number of struct records entered by user
{
if ((strcmp(s2[i].userName,c)==0)) //using strcmp for comparing strings
{
printf("struct variables are %d, %d, %s, %s\n", s2[i].id,s2[i].age,s2[i].userName,s2[i].dept);
break;
}
else if(i == num-1)
{
printf("nothing in userName matches: <%s>\n",c);
break;
}
}
}
void searchInt(student* s2,int num) //searchs for an integer and prints the entire structure
{
int i,z;
printf("please enter id to search ");
scanf("%d",&z);
printf("\n");
for (i=0;i<num;i++)
{
if (s2[i].id == z)
{
printf("struct variables are %d, %d, %s, %s\n\n", s2[i].id,s2[i].age,s2[i].userName,s2[i].dept);
break;
}
else if(i == num-1)
{
printf("nothing in id matches: <%d>\n\n",z);
break;
}
}
}
int main(void)
{
student *s2;
s2 = createArray();
addstruct(s2);
return 0;
}
I'm not going to go into optimizing, because if you wanted better theoretical performance you would probably go with different data structures, such as ordered arrays/lists, trees, hash tables or some kind of indexing... None of that is relevant in this case, because you have a simple program dealing with a small amount of data.
But I am going to tell you about the "excessive logic" your professor mentioned, taking your searchInt function as an example:
for (i=0;i<num;i++)
{
if (s2[i].id == z)
{
printf("struct variables are %d, %d, %s, %s\n\n", s2[i].id,s2[i].age,s2[i].userName,s2[i].dept);
break;
}
else if(i == num-1)
{
printf("nothing in id matches: <%d>\n\n",z);
break;
}
}
The thing here is that every time around the loop you're testing to see if you're at the last element in the loop. But the loop already does that. So you're doing it twice, and to make it worse, you're doing a subtraction (which may or may not be optimized into a register by the compiler).
What you would normally do is something like this:
int i;
student *s = NULL;
for( i = 0; i < num; i++ )
{
if( s2[i].id == z ) {
s = &s2[i];
break;
}
}
if( s != NULL ) {
printf( "struct variables are %d, %d, %s, %s\n\n",
s->id, s->age, s->userName, s->dept );
} else {
printf("nothing in id matches: <%d>\n\n",z);
}
See that you only need to have some way of knowing that the loop found something. You wait for the loop to finish before you test whether it found something.
In this case I used a pointer to indicate success, because I could then use the pointer to access the relevant record without having to index back into the array and clutter the code. You won't always use pointers.
Sometimes you set a flag, sometimes you store the array index, sometimes you just return from the function (and if the loop falls through you know it didn't find anything).
Programming is about making sensible choices for the problem you are solving. Only optimize when you need to, don't over-complicate a problem, and always try to write code that is easy to read/understand.

Resources