The question:
Read up to 6 pairs of names and ages into TWO separate arrays, and use a linear search to locate a target name and to print that person’s age. The two arrays are called names and ages:
I am getting lots of errors .. I am not sure about passing the arrays into functions..
#include <stdio.h>
#define ASIZE 20
#define RECSIZE 6
struct record {
char name[ASIZE];
int age[ASIZE];
};
struct record na[RECSIZE];
int linearSearch(struct record *a, char *find)
{
int x;
for(x=0; x<RECSIZE; x++)
{
// if(na[x].name==find[x])
if(a->name[x]==find[x])
{
return x;
}
}
return -1;
}
int main()
{
int i;
for (i=0; i<RECSIZE; i++)
{
printf("Enter name: ");
scanf("%s",na[i].name);
printf("Enter age: ");
scanf("%i",&na[i].age);
}
printf("Enter the Search name: ");
char temp[ASIZE];
scanf("%s",temp[ASIZE]);
int result;
result=linearSearch(&na, &temp[]);
printf("%i", result);
return 0;
}
Please help.
The error is in:
result=linearSearch(&na, &temp[]);
#include <stdio.h>
#include <string.h>
#define ASIZE 20
#define RECSIZE 6
struct record {
char name[ASIZE];
int age;
};
struct record na[RECSIZE];
int linearSearch(struct record *a, char *find){
int x;
for(x=0; x<RECSIZE; x++){
if(strcmp(a[x].name, find)==0)
return x;
}
return -1;
}
int main(){
int i;
for (i=0; i<RECSIZE; i++){
printf("Enter name: ");
scanf("%s", na[i].name);//No protection when entered past the buffer
printf("Enter age: ");
scanf("%i", &na[i].age);
}
printf("Enter the Search name: ");
char temp[ASIZE];
scanf("%s", temp);
int result;
result=linearSearch(na, temp);
printf("%i", result);
return 0;
}
On my system, the compiler gave me these errors for your exact code. Just look at the line numbers (should be exactly like yours) and address each error by looking at the error description. Once you address these, you will be further down the path of understanding your execution flow:
Related
#include <stdio.h>
void getScores(int a, char n[10][15], int s[10]) {
int score;
printf("Enter the number of students: ");
scanf("%d",&a);
for (int i=0; i < a;i++)
{
scanf("%s",n[i]);
scanf("%d",&score);
s[i]=score;
}
}
void printScores(int a, char n[10][15], int s[10] ) {
for (int i=0; i < a;i++)
{
printf("%s", n[a]);
printf(" ");
printf("%d\n",s[a]);
}
}
int main() {
char names[10][15];
int scores[10];
int num;
getScores(num,names,scores);
printScores(num,names,scores);
}
What I am trying to accomplish is have the parameter value of int a from the getScores function to be used in the printScores function as an array length as it is being used in getScores.
The arrays are saving its value when used in the print function but the a value is resetting to an unassigned number 896 when I need it to be what the user enters in the get function. Any tips?
Print scores will not print anything.
void getScores(int *a,
And the call
getScores(&num
You need also change accordingly the functions code
I'm new to C and I'm trying to create an online grocery store where I can add items to the store and print the details of each product such as the name, number in stock, price, etc.
I'm having trouble adding a product to a product collection array and getting it to print. My biggest issue is that main.c seems to not recognize practically every variable declared in defs.h even though I used the include tag at the top of the file. I'm also not sure if my addProd() function makes sense and was hoping someone could verify?
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "defs.h"
int main(){
InventoryType store;
store.storeName = "Walmart";
ProductCollectionType p;
p.numProd = 0;
addProd(&p, 1001, "Grape juice", 12.5);
addProd(&p, 1002, "Pepsi", 4.3);
addProd(&p, 1003, "Apples", 34.0);
int choice;
printf("(1) Print inventory");
printf("(0) Exit");
printf(" ");
printf("Please enter your choice: ");
scanf("%d", choice);
if(choice == 1){
store->printInventory(p)
}
return 0;
}
void printInventory(ProductCollectionType* productArray){
int i;
for(int i = 0; i < numProd; ++i) {
printf("The BLANK store");
printf("-- Product #%d, %s, %d units, $ %.2f", productArray[i].id, productArray[i]->name, productArray[i].numUnits, productArray[i].price);
}
}
int addProd(ProductCollectionType* productArray, int givenId, char givenName, int givenUnits, float givenPrice){
for(i = 0; i < numProd; ++i){
productArray[i].id = givenId;
productArray[i].name = givenName;
productArray[i].numUnits = givenUnits;
productArray[i].price = givenPrice;
}
}
defs.h
#define MAX_NAME 40
#define MAX_PROD 20
#define MAX_UNITS 15
typedef struct{
int id;
char *name;
int numUnits;
float price;
}ProductType;
typedef struct {
ProductType* products[MAX_UNITS];
int numProd;
int nextId;
}ProductCollectionType;
typedef struct{
char *storeName;
ProductCollectionType* productArray[MAX_PROD];
}InventoryType;
Regarding the code:
void printInventory(ProductCollectionType* productArray){
int i;
for(int i = 0; i < numProd; ++i){
blah blah blah
There is no such thing as the "naked" numProd, numProd is a field of the ProductCollectionType type. Hence you would need something like:
for (int i = 0; i < productArray->numProd; ++i) {
I cooked a code for a program that asks the user to fill in information about a person (ReadDate/ReadPerson), then it asks for the range of people the user wants to print, and the function prints these people. (PrintRange)
I don't understand why the program is not working; it's stuck on the point when it should print the person... it's means there is probably a problem in either PrintPerson or PrintDate, or in the way I am calling these functions.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
int day, month, year;
} Date;
typedef struct{
char *first_name, *last_name;
int id;
Date birthday;
} Person;
void ReadDate(Date *a)
{
printf("Enter the day: ");
scanf("%d", &a->day);
printf("Enter the month (1-12): ");
scanf("%d", &a->month);
printf("Enter the year: ");
scanf("%d", &a->year);
}
void ReadPerson(Person *b)
{
char temp_first_name[21];
char temp_last_name[21];
printf("Enter the first name: ");
gets(temp_first_name);
b->first_name = (char*)malloc(strlen(temp_first_name)+1);
strcpy(b->first_name,temp_first_name);
//need to check malloc (later)
printf("Enter the last name: ");
gets(temp_last_name);
b->last_name = (char*)malloc(strlen(temp_last_name)+1);
strcpy(b->last_name, temp_last_name);
//need to check malloc (later)
printf("Enter the id number: ");
scanf("%d",&b->id);
printf("Enter the birthday:\n");
ReadDate(&b->birthday);
}
int ReadAllDate (Person *b)
{
//Person* b;
int count=1;
char choice;
printf("Would you like to enter a person?(y,n)\n");
choice = getchar();
while(choice == 'y')
{
b = (Person*)malloc(1 * sizeof(Person));
getchar();
ReadPerson(b);
printf("Done!\n");
count++;
getchar();
printf("Would you like to add a person?(y,n)\n");
choice = getchar();
}
count--;
printf("The number of entered persons is %d\nBye\n", count);
return count;
}
void PrintPerson(Person b)
{
printf("%s %s %d\n", b.first_name, b.last_name, b.id);
}
void PrintDate(Date a)
{
printf("%d // %d // %d\n",a.day,a.month,a.year);
}
void PrintRange(Person *b,int count,int ind1,int ind2)
{
int i;
if (ind1<0 || ind1>ind2 || ind2>count)
{
printf("error! you slip out from the limits of the array.\n");
}
else
{
for (i=ind1; i<=ind2; i++)
{
PrintPerson(*(b+i));
PrintDate((b+i)->birthday);
}
}
}
int main(int argc, const char * argv[])
{
Person* b;
int count;
int ind1, ind2;
count = ReadAllDate(b);
printf("insert the first index (the smaller): ");
scanf("%d", &ind1);
printf("insert the second index (the bigger): ");
scanf("%d", &ind2);
PrintRange(b, count, ind1, ind2);
}
The problem is that nowhere you are actually creating an array of Person objects. The function ReadAllDate() never changes the value of the variable b in main(). Instead, for every person you read in, it allocates memory for it, and stores the pointer to that Person in the local variable b in ReadAllDate(). Every time it does it, it forgets the previous value of b.
In main(), the value of b is unitinialized all the time. When you are trying to print persons, it will most likely crash or print garbage.
I see other issues with your code:
Don't use gets(), always use fgets(). The former can write past the end of the buffer you are providing.
Don't do malloc(strlen(...))+strcpy(), use strdup().
Start with count = 0, that way you don't need the count-- in ReadAllDate(). As a computer programmer, it's best to count from zero instead of one.
Write b[i] instead of *(b+i), and b[i].birthday instead of (b+i)->birthday.
I have got this template.
#include <stdio.h>
#include <string.h>
#define SIZE 10
int findTarget(char *target, char nameptr[SIZE][80], int size);
int main()
{
char nameptr[SIZE][80];
char t[40];
int i, result, size;
printf("Enter no. of names: ");
scanf("%d", &size);
printf("Enter %d names: ", size);
for (i = 0; i<size; i++)
scanf("%s", nameptr[i]);
printf("Enter target name: ");
scanf("\n");
gets(t);
result = findTarget(t, nameptr, size);
printf("findTarget(): %d\n", result);
return 0;
}
int findTarget(char *target, char nameptr[SIZE][80], int size)
{
/* write your code here */
int i;
for (i = 0; i < size; i++) {
if (nameptr[i] == *target)
return i;
}
return -1;
}
And the code under /* write your code here */ is my code.
The code doesn't work. I think something is wrong with (nameptr[i] == *target).
Examples of output:
Enter no. of names: 4
Enter 4 names: Peter Paul John Mary
Enter target name: John
findTarget(): 2
Enter no. of names: 4
Enter 4 names: peter mary john steve
Enter target name: may
findTarget(): -1
I think the template is correct cos its provided by school.
Thank you for helps.
This:
if (nameptr[i] == *target)
is wrong because you are comparing a pointer with an integer and that makes no sense. Also, in order to compare two strings, use strcmp. Using == will compare the pointers and not the content of them.
Fix:
if (strcmp(nameptr[i], target) == 0)
I've tried malloc, and no malloc and it will build but not run or compile. When I run the code on codepad.org it gives me a segmentation error. I have an array of structures I'm inputting and I'm searching through them for a specific item. That's as far as I got and no compile. The code is as follows (I used netbeans, codeblocks, and visual basic 2012 programs):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 20
#define BLOODTYPESIZE 4
#define MAX 120000
typedef struct {
int month;
int day;
int year;
} dateT;
typedef struct {
int hour;
int minute;
} timeT;
typedef struct {
char name[SIZE];
char organname[SIZE];
char bloodtype[BLOODTYPESIZE];
dateT dateAdded;
timeT timeAdded;
int received;
} organT;
int main(void) {
int i, n, k, j;
int c;
int *ptr;
char organ[SIZE];
char bloodkind[BLOODTYPESIZE];
organT patient[MAX];
scanf("%d",&n);
ptr = (int *)malloc(n * sizeof(*ptr));
printf("Enter patient information\n");
for(i=1; i<=n; i++){
scanf("%s", patient[i].name[SIZE]);
scanf("%s", patient[i].organname[SIZE]);
scanf("%s", patient[i].bloodtype[BLOODTYPESIZE]);
scanf("%d %d %d", patient[i].dateAdded);
scanf("%d %d", patient[i].timeAdded);
patient[i].received = 0;
}
scanf("%d", &k);
for(j=0; j<k; j++) {
gets(organ);
printf("Organ received: %s", organ);
gets(bloodkind);
printf("Organ has blood type: %s", bloodkind);
}
for (c=0; c<n; c++){
if(patient[i].organname == organ){
if(patient[i].bloodtype == bloodkind){
if(patient[i].received == 0) {
printf("Patient(s) Found!\n");
printf("%s", patient[i].name[SIZE]);
printf("Organ received: %s", organ);
patient[i].received = 1;
}
if(patient[i].received == 1)
printf("Patient already received organ\n");
}
else("Not correct blood type\n");
}
else("No match found\n");
}
return (EXIT_SUCCESS);
}
Looks like you are not using the address correctly. For example, when you say
scanf("%s", &patient[i].name[SIZE]);
you are actually reading past the allocated space for patient[i].name. You should change the statement to
scanf("%s",patient[i].name);
and fix other statements similarly.
First check n compare to MAX
here you access to bloodtype[BLOODTYPESIZE] but the last item in this tab is bloodtype[BLOODTYPESIZE-1]
scanf("%s", &patient[i].bloodtype[BLOODTYPESIZE]);
The same problem is tru for other acces in the pararagraph.