Don't know how to call function - c

I am writing a search function in C which uses pointers and structs. Search is possible by name using an array called contatcs with ten entries. The array has already been initialized and populated and works as intended.
I have tried to fix the problem by restructuring my code, but it only made matters worse. Maybe there is some flaw in the design logic that I cannot find.
typedef struct
{
char streetname[150];
char city[50];
int zipcode;
}address;
typedef struct
{
char name[50];
int age;
address homeaddress;
}person;
int search (char* name, person *contacts, int size);
[...] // initialization and population of array omitted
int search (char *name, person *contacts, int size)
{
int i;
printf("Input name: ");
char userin = scanf("%s", name);
for(i = 0; i < size; i++)
{
if (strcmp(contacts[i].name, &userin) == 0)
{
printf("Name: %s;", contacts[i].name);
printf(" Age: %d;", contacts[i].age);
printf(" Adress: %s, ", contacts[i].homeaddress.streetname);
printf("%s, ", contacts[i].homeaddress.city);
printf("%d\n", contacts[i].homeaddress.zipcode);
}
}
return 0;
}
I am just trying to call the function. But every time I try to do so, it just doesn't work. I know this question is rather basic, but I can't seem to find the solution.

char userin = scanf("%s", name);
for(i = 0; i < size; i++)
{
if (strcmp(contacts[i].name, &userin) == 0)
You can not use strcmp with a char, userin must be a NUL terminated array of chars
And as pointed out by #JohnBollinger in comments, it seems you want to compare the name, not the result of scanf

Related

C - "error: Cannot access memory at address" occurs

#include <stdio.h>
#include <string.h>
typedef struct birth{
char *name;
char time[12];
}birth;
void swap(struct birth *a, struct birth *b){
struct birth tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
int main(){
int n;
birth list[100], *p, *q;
scanf("%d", &n);
getchar();
for(p = list; p < list + n; p++){
scanf("%s %s", &p->name, &p->time);
}
for(p = list; p < list + n - 1; p++){
for(q = p + 1; q < list + n; q++){
if(strcmp(p->time, q->time) > 0){
swap(p ,q);
}
else if(strcmp(p->time, q->time) == 0){
if(strcmp(p->name, q->name) > 0){
swap(p ,q);
}
}
}
}
for(int i = 0; i < n; i++){
printf("%s %s\n", list[i].name, list[i].time);
}
return 0;
}
I am solving the problem of receiving n, which means the number of students, repeating the number of students, receiving the student's name and date of birth, and printing the names in advance if the date of birth is the same.
However, there was no answer, so I checked using the debugger in vcode, and when I received the input, the date of birth was well entered, but the name was not.
You are trying to read a string using a char pointer that was never initialized.
typedef struct birth{
char *name;
char time[12];
}birth;
...
scanf("%s %s", &p->name, &p->time); // error, &p->name points to nowhere
You should either allocate memory yourself or declare it as a fixed size char array. It would be best to check the string boundaries too:
#define S_NAME 12
#define S_TIME 12
typedef struct birth{
char name[S_NAME];
char time[S_TIME];
}birth;
...
// read string with safety guard
if (fgets(p->name, S_NAME, stdin) != NULL) {
// read name successfully
}
if (fgets(p->time, S_TIME, stdin) != NULL) {
// read time successfully
}

segmentation fault using malloc

I'm new to C, so this may be a silly question to ask:
What I want to do here is to input the data to the array of pointers to a structure and then print it out. But I get a segmentation fault when running into the insert function.
Below is my code
common.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct book * Book;
struct book{
int id;
char *name;
};
extern int b_insert(Book *b, int id, char *name);
extern int b_print(Book books[], int len);
insert.c
#include "common.h"
int b_insert(Book *b, int id, char *name){
Book p;
p = (Book)malloc(sizeof(struct book));
p->id = id;
strcpy(p->name, name);
*b = p;
printf("success insert book:\n");
printf("\tID: %d Name: %s\n", (*b)->id, (*b)->name);
return 0;
}
int b_print(Book books[], int len){
int i;
printf("Book List\n");
for(i=0; i<len; i++){
printf("books[%d] = ID: %d, Name: %s\n", i, books[i]->id, books[i]->name);
}
return 0;
}
main.c
#include "common.h"
#define MAX 2
int main(){
Book books[MAX];
Book *b=books;
int i;
int id;
char name[10];
for(i=0; i<MAX; i++){
printf("please input new books info\n");
printf("ID: ");
scanf("%d", &id);
printf("Name: ");
scanf("%s", name);
if(b_insert(b, id, name) == -1){
printf("fail to insert\n");
}
b++;
}
b_print(books, MAX);
return 0;
}
Main problem:
Allocate memory for p->name before using
strcpy(p->name, name);
using malloc:
p->name = malloc(10); //Or some other size
Other problems:
Remove the cast here:
p = (Book)malloc(sizeof(struct book));
Why? Here is the answer
if(b_insert(b, id, name) == -1){ will never be true.
Check the result of malloc to check if it was successful in allocating memory.
Check the return value of all the scanfs to see if it was successful in scanning data.
Add a length modifier to the second scanf to prevent buffer overflows:
scanf("%9s", name); /* +1 for the NUL-terminator */
You're not allocating space for name:
int b_insert(Book *b, int id, char *name){
Book p;
p = malloc(sizeof(struct book));
if (p != NULL)
{
p->name = malloc(strlen(name)+1); // It allocates space where the input name will be copied.
if (p->name != NULL)
{
p->id = id;
strcpy(p->name, name);
*b = p;
printf("success insert book:\n");
printf("\tID: %d Name: %s\n", (*b)->id, (*b)->name);
}
else return -1; // No space to allocate string
}
else return -1; // No space to allocate struct
return 0;
}
As mentioned before, allocate space for p->name. You should probably also use something different to read the book title, either scanf format %ms with a pointer to a char pointer, or %9s with your buffer, otherwise the title "war or peace" will also result in a segfault.
Here you create a static variable and the space for it is allocated automatically.
Book p;
You can allocate a space manually when you assign it to pointer, in this line it's not pointer but static variable.
p = (Book)malloc(sizeof(struct book));
What's more if you want to refer to attribute of static variable you should use "." instead of "->". So you have two option. Create a pointer and allocate a space for the structure and then you "->" oraz create static variable.
p->id = id;

scanf does not work

im implementing a program that reads student id and names from stdin or file, and make them ordered by name and ordered by number. The funny thing is i cant understand why but scanf doesnt work. Here is my code while using scanf:
int n=0;
while(n<SIZE){
scanf("%d %s\n",&std_array[n].id, std_array[n].name);
n++;
}
for(int i=0; i<SIZE; i++)
printf("%d %s\n",std_array[i].id,std_array[i].name);
and here is my struct:
struct Student {
char *name;
int id;};
when i read from file and print them the out put is:
> 12586546 (null) 0 (null) 0 (null) 0 (null) 0 (null) 0 (null) 0 (null)
> 0 (null) 0 (null) 0 (null)
although file have some numbers and names like 21456764 john 45797654 fred etc. , its doesn't read successfully.
NOTE: i know the way we fix struct like you guys suggested but i must learn the way to do this with char pointer...
When doing this:
struct Student {
char *name; // This does not allocate memory
int id;};
Here, name is a pointer, with no allocated memory, behaving like an uninitialized literal string.
Trying to modify it creates undefined behaviour.
Replace with:
struct Student {
char name[50];
int id;};
or
struct Student {
char name[] = "Initial value gives maximum length. Do not write more!";
int id;};
This allocates memory to the pointer as needed. An intermediate variable is used to hold the string then only enough memory plus 1 for the terminating '\0' is allocated in the struct.
int n=0;
char name[100];//longest possible name
while(n<SIZE && ( scanf("%d%99s",&std_array[n].id, name) == 2)) {// successfully scanned two items
std_array[n].name = malloc ( strlen ( name) + 1));
if ( std_array[n].name == NULL) {
printf ( "malloc failed\n");
// break or return or exit(1) as appropriate
}
strcpy ( std_array[n].name, name);
n++;
}
for(int i = 0; i < n; i++)
printf("%d %s\n",std_array[i].id,std_array[i].name);
Eventually you will want to free the memory
for ( i = 0; i < n; i++) {
free ( std_array[i].name);
}
Point 1
Allocate memory to name before using it. Otherwise, if used uninitialized, it does not point to any valid memory to read from or write into. You can use malloc() to allocate memory. Also, once done, don't forget to free() it once you're done using the memory.
Point 2
Remove the \n from scanf().
This is the corrected code
struct Student
{
char name[20];
int id;
};
struct Student std_array[SIZE];
int n=0;
while(n<SIZE)
{
scanf("%d %s", &std_array[n].id, std_array[n].name);
n++;
}
n=0;
while(n<SIZE)
{
printf("%d %s\n", std_array[n].id, std_array[n].name);
n++;
}
Hope this helps...,
as user3121023 told to me, it worked. fixed code is following:
struct Student {
char *name;
int id;
};
struct Student std_array[SIZE];
int cmpfunc (const void * a, const void * b);
struct Student *order_by_number(struct Student *array);
int main(int argc, char **argv){
int n=0;
char name[100];
while(n<SIZE){
scanf("%d %s\n",&std_array[n].id, name);
std_array[n].name = malloc(strlen(name)+1);
strcpy(std_array[n].name ,name);
n++;
}
for(int i=0; i<SIZE; i++)
printf("%d %s\n",std_array[i].id,std_array[i].name);
order_by_number(std_array);
for(int i=0; i<SIZE; i++)
printf("%d %s\n",std_array[i].id,std_array[i].name);
}
im done, ty guys for helping me. CASE CLOSED :)

Reading file data to array of structures while allocating memory dynamically

I need help solving the code below. After the code is compiled using gcc it can be run like ./compiledFile inputFile.txt It should take the inputFile.txt read it while allocating memory dynamically for each variable in this case name and courseID, but my code is not working. The place that I don't understand the most and need help is allocating memory, inserting data into structures and printing the data like the example given below. By the look of this code you could tell that I am a newbie to c and dynamic memory allocation and structure in all.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct people
{
char* name[10];
char* courseID[15];
int grade;
};
void printData(struct people student[], int count);
int main(int argc, char* argv[])
{
FILE *in_file;
char buffer[30];
char *token, *del=",";
int count=0;
struct people student[20];
if(( in_file = fopen(argv[1], "r")) == NULL)
{
printf("unable to open the file");
}
while (fgets(buffer, sizeof(buffer), in_file))
{
student = malloc(sizeof(struct people));
token = strtok(buffer, del);
strcpy(student[count].name, token);
count++;
}
fclose(in_file);
printData(student, count);
}
void printData(struct people student[], int count)
{
int i;
for(i=0; i<count; i++)
{
printf("%s", student[i].courseID);
if (strcmp((student[i].name, student[i].courseID) > 0))
{
printf("%s %s", student[i].name, student[i].grade)
}
}
}
the data.txt file has the following content separated by a comman:
John,MATH 1324,90
David,SCI 1401,88
Omondi,MATH 1324,89
David,MATH 1324,90
when printed out it should look like the following:
MATH 1324
John 90
Omondi 89
David 90
SCI 1401
David 88
first of all, it would be great if you could also share what is the actual output or error you get while running this program.
most of the time dynamic memory allocation is used when we do not know the actual size of data elements, but here you have already fixed the size of struct people student as 20
struct people student[20];
this is absolutely fine, but then you do malloc in while loop
student = malloc(sizeof(struct student);
you have already alloted 20 locations using array declaration, now malloc is not required.
if you want to use dynamic memory allocation using pointers for learning purpose then you should first declare student as pointer to type struct people
struct people* student;
allocate memory dynamically in while loop
student=(struct people*) malloc(sizeof(struct people));
then access it
*(student+count)
hope this helps, if you still have doubts/problems edit the question and include the output/error you get while compiling/running this program.
Several issues with the Question code...
1) Definition of main():
int main(int argc, char* argv[])
It must return an integer. Add a return statement at the end of main(), and make a proper "CLEANUP" section:
printData(student, count);
CLEANUP:
if(in_file)
fclose(in_file);
return(0);
}
2) Better handling of fopen() error condition:
if(( in_file = fopen(argv[1], "r")) == NULL)
{
printf("unable to open the file");
goto CLEANUP;
}
And, initialize the in_file pointer:
int main(int argc, char* argv[])
{
FILE *in_file = NULL;
3) Next, the exact definition of student needs to be established. Is it a static array, or is a pointer to a dynamically allocated array? I will assume that you would like to use a dynamic array (given the question text). However, this assumption conflicts with the following line, which defines student as a static array:
struct people student[20];
Change it to:
struct people *student = NULL;
4) Now, the following question code allocates a new (separate) chunk of memory for each student:
student = malloc(sizeof(struct people));
However, what is needed is all the student records in one array, in the same chunk of memory. So, what is needed is to expand a chunk of memory to include student records as they are read, like this:
while (fgets(buffer, sizeof(buffer), in_file))
{
void *tmp = realloc(student, sizeof(struct people) * (count + 1));
if(NULL == tmp)
{
printf("realloc() failed.\n");
goto CLEANUP;
}
student = tmp;
token = strtok(buffer, del);
5) Take a look at the people structure:
struct people
{
char* name[10];
char* courseID[15];
int grade;
};
It appears that the question code has some difficulty when it comes to pointers & arrays. The code is attempting to define the name and courseID fields as both pointers, and arrays. Given that the question is to do with dynamically allocating stuff, I elect to go that direction. Hence, this structure should be changed to the following:
struct people
{
char *name;
char *courseID;
int grade;
};
6) So, each time through the loop, the student name will be placed in allocated storage, and pointed to by the .name field. So, change this:
token = strtok(buffer, del);
strcpy(student[count]->name, token);
count++;
}
to this:
token = strtok(buffer, del);
student[count].name = strdup(token);
count++;
}
7) I don't understand the intent of this line:
if (strcmp((student[i].name, student[i].courseID) > 0))
I am inclined to eliminate it.
8) The following line has flaws:
printf("%s %s", student[i].name, student[i].grade)
Change it to this to print the integer grade (and don't forget the ending semicolon):
printf("%s %d\n", student[i].name, student[i].grade);
The '\n' makes the output look better, one record per line.
9) Since student is a pointer to dynamically allocated memory (not a static array), change this:
void printData(struct people student[], int count)
to this:
void printData(struct people *student, int count)
10) Now, finish the task of parsing the data; from this:
token = strtok(buffer, del);
strcpy(student[count].name, token);
count++;
}
to this:
token = strtok(buffer, del);
student[count].name = strdup(token);
token = strtok(NULL, del);
student[count].courseID = strdup(token);
token = strtok(NULL, del);
student[count].grade = strtol(token, NULL, 10);
count++;
}
11) Now, to make life easier, sort the array. First by courseID, then by name:
...
count++;
}
/** Sort the array by coursID, then by name. **/
qsort(student, count, sizeof(*student), CmpStudentRecs);
printData(student, count);
...
Which will require an additional "Compare Student Recs" function:
int CmpStudentRecs(const void *recA, const void *recB)
{
int result = 0;
struct people *stuRecA = (struct people *)recA;
struct people *stuRecB = (struct people *)recB;
/** First compare the courseIDs **/
result=strcmp(stuRecA->courseID, stuRecB->courseID);
/** Second (if courseIDs match) compare the names **/
if(!result)
result=strcmp(stuRecA->name, stuRecB->name);
return(result);
}
12) Some finishing touches with the printData() function:
void printData(struct people *student, int count)
{
int i;
char *courseID = "";
for(i=0; i<count; i++)
{
if(strcmp(courseID, student[i].courseID))
{
printf("%s\n", student[i].courseID);
courseID = student[i].courseID;
}
printf("\t%s %d\n", student[i].name, student[i].grade);
}
}
Finished. Output:
SLES11SP2:~/SO> ./test data.txt
MATH 1324
David 90
John 90
Omondi 89
SCI 1401
David 88
SLES11SP2:~/SO>
SPOILER
Change the definition of people to:
struct people
{
char name[10];
char courseID[15];
int grade;
};
This assumes that name won't be longer than 9 characters and coursID won't be longer than 14 characters. If that is not true, change them accordingly.
The line:
student = malloc(sizeof(struct student);
is wrong in couple of ways.
student is already declared to be an array of people. You cannot assign it to point to memory allocated by malloc.
struct student is not a type.
That line can be removed.
The line
strcpy(student[count].name, token);
can cause problems if the length of token is longer than 10 (or whatever size you choose for name in people). The safer thing to do is use strncpy.
strncpy(student[count].name, token, 10);
student[count].name[9] = '\0';
You have not set the value of courseID anywhere. Yet, you are trying to print it in printData. You are doing the same thing for grade. You need to update the processing of input lines to set those correctly.
Change the while loop to:
while (fgets(buffer, sizeof(buffer), in_file))
{
token = strtok(buffer, del);
strncpy(student[count].name, token, 10);
student[count].name[9] = '\0';
token = strtok(NULL, del);
strncpy(student[count].courseID, token, 15);
student[count].courseID[14] = '\0';
token = strtok(NULL, del);
student[count].grade = atoi(token);
count++;
}
There are couple of syntax errors in printData. However, fixing those syntax errors does not take care of your printing requirements. It will be easier to print the data in the order that you want to if you sort the data. The following functions will help you sort the data.
int compareStudent(const void* ptr1, const void* ptr2)
{
struct people* p1 = (struct people*)ptr1;
struct people* p2 = (struct people*)ptr2;
return (strcmp(p1->courseID, p2->courseID));
}
void sortData(struct people student[], int count)
{
qsort(student, count, sizeof(struct people), compareStudent);
}
You can call sortData before calling printData or call sortData first in printData. The logic for printing the data needs to be updated a little bit. Here's an updated printData.
void printData(struct people student[], int count)
{
int i;
int j;
sortData(student, count);
for(i=0; i<count; ++i)
{
printf("%s\n", student[i].courseID);
printf("%s %d\n", student[i].name, student[i].grade);
for ( j = i+1; j < count; ++j )
{
if (strcmp(student[i].courseID, student[j].courseID) == 0)
{
printf("%s %d\n", student[j].name, student[j].grade);
}
else
{
i = j-1;
break;
}
}
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct people {
char name[10];//char *name[10] is array of pointer
char courseID[15];
int grade;
};
void printData(struct people student[], int count);
int main(int argc, char* argv[]){
FILE *in_file;
char buffer[30];
char *token, *del=",";
int count=0;
struct people student[20];
if((in_file = fopen(argv[1], "r")) == NULL){
printf("unable to open the file");
return -1;//It is not possible to continue the process
}
while (fgets(buffer, sizeof(buffer), in_file)){
//student = malloc(sizeof(struct people));//It is by securing an array already
token = strtok(buffer, del);
strcpy(student[count].name, token);
token = strtok(NULL, del);
strcpy(student[count].courseID, token);
token = strtok(NULL, del);
student[count].grade = atoi(token);
count++;
}
fclose(in_file);
printData(student, count);
}
int cmp(const void *a, const void *b){
const char *x = ((const struct people*)a)->courseID;
const char *y = ((const struct people*)b)->courseID;
return strcmp(x, y);
}
void printData(struct people student[], int count){
qsort(student, count, sizeof(struct people), cmp);//sort by courseID
char *prev = "";
int i;
for(i=0; i<count; i++){
if(strcmp(prev, student[i].courseID)!=0){
prev = student[i].courseID;
printf("\n%s\n", prev);
}
printf("%-9s %d\n", student[i].name, student[i].grade);
}
}

How to dynamically allocate a two dimensional array of pointers ? (C)

I have an assignment to make a dictionary.
It will contain an x amount of words and their definitions (input by user).
Instructions say that the dictionary should be of type char*** (2D array of pointers=arrays=strings), but I've got absolutely no idea of how to dynamically allocate the size of the array. it should have 2 lines, 1 for words and another 1 for their definitions, and the number of columns is decided by how many words are in the dictionary. While looking for help online i came up with this:
char** AllocateArray(int line, int column)
{
char** pArray=(char**)malloc(line*sizeof(char*));
int i;
for(i=0;i<2;i++)
pArray[i]=(char*)malloc(column*sizeof(char));
return pArray;
}
What changes should i make in the code for it to work with my char*** ?
Using Visual studio 2012
Edit:
I have a problem with this right now:
void inputString(char* p1)
{
char buffer[80];
printf("\nEnter a word:");
scanf("%s",buffer);
p1=(char*)malloc(strlen(buffer)+1);
if(p1!=NULL)
{
strcpy(p1,buffer);
free(buffer);
}
}
it crashes right after i input a word. the char* that the function receives is dictionary[i][j]. –
Don't free() anything allocated on the stack (i.e. buffer).
Also, your function inputString() will not tell its client what memory it had allocated, since p1 is local to it.
Here is an example.
char*** dictionary;
int i = 0;
int j = 0;
int lines = 10;
dictionary = (char***)malloc(sizeof(char**)*lines);
for(i=0;i<lines;i++)
{
dictionary[i] = (char**)malloc(sizeof(char*)*4);
for(j=0;j<4;j++)
dictionary[i][j] = (char*)malloc(sizeof(char)*25);
}
You have to modify the malloc's parameters in order to adapt to your problem/ or modify them when you need more memory for your strings.
Also it might be a good idea to try and free memory when you do not need it
Don't forget to malloc like this...
dictionary[i][j] = (char*)malloc(sizeof(char)*strlen(word_to_insert)+1);
...because each word end with a supplementary byte filled with 0 "null terminate string".
a sample
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char ***dictionary;
const char *words[] = { "ASEAN", "United Nations", "OPEC" };
size_t howManyWords = sizeof(words)/sizeof(*words);
int i;
dictionary = malloc(howManyWords*sizeof(char**));
printf("Please enter the definition of this word\n");
for(i = 0; i < howManyWords; ++i){
char buff[80];
char **keyValue;
printf("%s : ", words[i]);
fgets(buff, sizeof(buff), stdin);
keyValue = malloc(2*sizeof(char*));
keyValue[0] = (char*)words[i];
keyValue[1] = malloc(strlen(buff)+1);
strcpy(keyValue[1], buff);
dictionary[i] = keyValue;
}
//print
for(i=0;i<howManyWords;++i){
printf("%s : %s", dictionary[i][0], dictionary[i][1]);
}
//release
for(i=0;i<howManyWords;++i){
free(dictionary[i][1]);
free(dictionary[i]);
}
free(dictionary);
return 0;
}

Resources