Reading strings to an array - c

Im doing a practice execise for my Coding class and Cant for the love of me figure out how to Fix it, The strings work within the loop but for some reason I cant read them to an array so I can pull them back to work with them later.
Ive been having troubles grabbing my strings that im making in the first loop in main, and it has been killing me cause ive tried multiple different solutions with none working
Here is the code ive currently writen
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 10
typedef struct {
char name[MAX_LEN];
char food[MAX_LEN];
char sound[MAX_LEN];
} Animal;
/*Takes a pointer to an Animal struct and returns nothing*/
void getAnimal(Animal* type);
/*Takes a pointer to an Animal and returns nothing*/
void visitAnimal(Animal* type);
int main() {
int i = 0;
int count = 0;
Animal type[MAX_LEN] = {};
printf("How many Animals Are there on the farm?: ");
scanf("%d", &count);
for (i = 0; i < count; ++i) {
getAnimal(type);
}
printf("Welcome to our farm.\n");
for (i = 0; i < count; ++i) {
visitAnimal(type);
}
return 0;
}
/**/
void getAnimal(Animal* type) {
printf("Enter the name of the animal: ");
scanf("%s", type->name);
printf("What does a %s eat?: ", type->name);
scanf("%s", type->food);
printf("Enter the sound made by a %s: ", type->name);
scanf("%s", type->sound);
}
/**/
void visitAnimal(Animal* type) {
printf("This is a %s. It eats %s and says %s\n", type->name, type->food,
type->sound);
}
sh-4.2$ gcc -ansi -Wall PE10.c
sh-4.2$ a.out
How many Animals Are there on the farm?: 2
Enter the name of the animal: cow
What does a cow eat?: wheat
Enter the sound made by a cow: moo
Enter the name of the animal: Duck
What does a Duck eat?: seeds
Enter the sound made by a Duck: quack
Welcome to our farm.
This is a Duck. It eats seeds and says quack
This is a Duck. It eats seeds and says quack

you are passing the same struct into getAnimal each time
for (i = 0; i < count; ++i) {
getAnimal(type);
}
you need instead
for (i = 0; i < count; ++i) {
getAnimal(&type[i]);
}

In these calls, the array type decays into a pointer to the first Animal in the array:
getAnimal(type);
visitAnimal(type);
In order to supply a pointer to the i:th Animal:
getAnimal(type + i); // or getAnimal(&type[i]);
visitAnimal(type + i); // or visitAnimal(&type[i]);

Related

Why array of strings passed from function cannot be read?

I need to pass array of strings from a function to another function. However, the array of strings in my 2nd for-loop couldn't read inputs from my 1st for-loop. I'm wondering if the format to pass array of strings I wrote is wrong?
No error was shown in CodeBlocks during compilation.
What should I do? (I'm a beginner in both programming and c)
Sorry for the lengthy codes previously, this is the minimalized ver of my code.
By the way, input from user is one of the requirements in the question.
#include <stdio.h>
#include <stdlib.h>
void itemInput();
void display_output(int,char*,float*);
int main()
{
itemInput();
}
void itemInput()
{
int i, itemNum;
char itemName[i]; float itemPrice[i];
printf("Insert number of items: ");
scanf("%d",&itemNum);
for(i=0;i<itemNum;i++)
{
printf("Item %d:",i+1);
scanf("%s",&itemName[i]);
printf("Price:RM");
scanf("%f",&itemPrice[i]);
}
display_output(itemNum,itemName,itemPrice);
void display_output(int numItem, char *nameItem, float *priceItem)
{
int i;
for(i=0;i<numItem;i++)
{
printf("%s , RM%.2f",nameItem[i],priceItem[i]);
}
}
Your program has the following errors:
The i is declared but initialized nowhere and you're trying to initialize the array with its garbage value, but the array isn't even initialized properly.
It seems like you're trying to store the entire %s in a single (one) char array which is impossible.
You're passing an uninitialized array into the argument which asks you for a pointer.
The arguments' memory were never allocated to use them correctly.
Rather than using a single variable to store multiple names or using multidimensional arrays, take a little benefit of struct to create a structure as array and store the variable in it.
Here's the clear program:
#include <stdio.h>
#define MAX 100
struct Item {
char name[MAX];
float price;
};
void get_item_info(int, Item[]);
int main(void) {
Item item[MAX];
int num = 0;
printf("How many items to add? ");
scanf("%d", &num);
for (int i = 0; i < num; i++) {
printf("--- ITEM %d ---\n", (i + 1));
printf("Item name: ");
scanf("%s", item[i].name);
printf("Item price: ");
scanf("%f", &item[i].price);
}
get_item_info(num, item);
return 0;
}
void get_item_info(int n, Item it[]) {
for (int i = 0; i < n; i++) {
printf("Item %d's name: %s\n", (i + 1), it[i].name);
printf("Item %d's price: %.2f\n", (i + 1), it[i].price);
}
}
The function get_item_info() simply gets all the values containing in each container of Item struct and displays using a for loop.
Sample output of the above code:
$ gcc -o prog prog.c; ./prog
How many items to add? 2
--- ITEM 1 ---
Item name: Books_Of_C
Item price: 500.25
--- ITEM 2 ---
Item name: Ice_Creams
Item price: 25
Item 1's name: Books_Of_C
Item 1's price: 500.25
Item 2's name: Ice_Creams
Item 2's price: 25.00

Unwanted output on second pass using strcpy

I'm reading a book called "C programming Absolute Beginners Guide."
The following program uses some if loops and strcpy to store some character arrays provided by the user. The first pass of strcpy works fine. The second produces garbage. I understand the array needs a \0 to end. According to the book, strcpy does this automatically. What am I missing?
#include <stdio.h>
#include <string.h>
main()
{
int ctr, numMovies, rating, favRating, leastRating;
char movieName[40], favorite[40], least[40];
favRating = 0;
leastRating = 0;
do {
printf("How many movies have you seen this year? ");
scanf(" %d", &numMovies);
if (numMovies < 1)
{
printf("No movies! How can you rank them?\nTry again\n\n");
}
} while (numMovies < 1 );
for (ctr = 1; ctr <= numMovies; ctr++)
{
printf("\nWhat's the name of the movie? ");
printf("(1-word titles only!) ");
scanf(" %s", movieName);
printf("On a scale of 1 to 10, what would ");
printf("you rate it? ");
scanf(" %d", &rating);
if (rating > favRating)
{
strcpy(favorite, movieName);
favRating = rating;
}
printf("%s", movieName);
if (rating < leastRating)
{
strcpy(least, movieName);
leastRating = rating;
}
}
printf("\nYour Favorite Movie was %s.\n", favorite);
printf("\nYour Least-favorite movie was %s.\n", least);
return 0;
}
Because you initialize leastRating to zero you won't have a least favorite unless the rating is negative. Not sure that's what you want.
The best suggestion is from #xing, add a include
#include <limits.h>
and initialize you best and worst like this;
favRating = INT_MIN;
leastRating = INT_MAX;

Issue with getting user input into a Dynamic array C

I seem to be having trouble getting user input into a dynamic array in C.
#include "stdio.h"
int main(void){
int counter = 0;
int x = 1;
int i;
printf("Enter the number of teams playing in the league: \n");
scanf("%d", &i);
char teams[i];
for (counter = 0; counter < i; counter++){
char teams[counter];
printf("Enter team names: \n");
scanf("%s", teams);
}
for (counter = 0; counter < i; counter++){
char teams[counter][10];
printf(" Team %d is %s \n", x, *teams);
x++;
}
}
When I run this code I get a the following output,
Enter the number of teams playing in the league: 2
Enter team names: Team1
Enter team names: Team2
Team 1 is Team1
Team 2 is \320\365\277\357\376
Program ended with exit code: 0
Not able to figure out my mistake. Would love any and all help.
Thank You!
There are some basic mistakes, especially with your understanding of pointers and C language concepts. "team" is an array of char pointers, and char teams[i] isn't quite correct; one correct way is to dynamically allocate memory for the collection of team names. By comparing the code below to yours, I am sure you can spot the areas where you made mistakes. PS: I am using the format character "m" inside scanf to dynamically allocate memory for the team name.
int main(int argc, char **argv){
int counter = 0;
int i, ret;
char **teams;
printf("Enter the number of teams playing in the league: \n");
scanf("%d", &i); // check return value yourself
teams=(char **)malloc(sizeof(char *)*i);
if(NULL==teams) perror("not enough memory"), exit(1);
for (counter = 0; counter < i; counter++){
printf("Enter team names: \n");
ret=scanf("%ms", &teams[counter]);
if(ret<1)//hanndle error. i'll just quit.
exit(-1);
}
for (counter = 0; counter < i; counter++){
printf(" Team %d is %s \n", counter+1, teams[counter]);
free(teams[counter]);
}
free(teams);
}

Lottery Program Problems

I'm currently in progress of creating my second main C program. I've only just started to learn C and I've had a few problems, as well confusion on what to do next with this program.
The idea is to basically allow the user to enter in a desired amount of years, then the program simulates the lottery games played every week, depending on how many years they enter. Then inside the program, I want the two arrays to compare to each other and check for any numbers they both have at the same time. The lottery ticket on the user's end stays the same, which is set inside the array and of course, the random lottery numbers change every week.
The basics are done, I'm just having a few problems, as well as not knowing where to go in certain areas.
Problems:
"int weeks = year * 52" doesn't work, says the initializer element isn't constant.
When I return the get_lotto_draw, I just get a bunched up number, it's not seperated in anyway, so I'm not sure how to do that.
#include <stdio.h> //Alows input/output operations
#include <stdlib.h> //Standard utility operations
//Declaring Variables
int year;
char name[15];
char option;
int lotteryPlayer[] = {5,11,15,33,42,43};
int i;
int randomNums[49];
int *lotteryPtr = lotteryPlayer;
int *randomPtr = randomNums;
int weeks = 0;
void print_array(int *lotteryPtr);
int* get_lotto_draw(int *randomPtr);
//Main Method
int main(int argc, char *argv[])
{
start: //Start of program
printf("\n---------------------------");
printf("\nProject: Jackpot Dreams ");
printf("\n---------------------------\n");
printf("\nWhat is your First Name?:> "); //Asks them for their choice
scanf("%s", &name); //Reads the input
printf("\nHow Many Years to Sleep?:> "); //Asks them for their choice
scanf("%d", &year); //Reads the input
weeks = year * 52;
printf("\nOk %s, I will play the lottery for %d years!\n",name, year);
sleep(1500);
printf("Sweet Dreams %s, don't let the bed bugs bite", &name);
sleep(1500);
printf(". ");
sleep(1500);
printf(". ");
sleep(1500);
printf(".");
sleep(2000);
printf("%d", get_lotto_draw);
system("PAUSE");
}
//Returns an array of six random lottery numbers 1-49
int* get_lotto_draw(int *randomPtr)
{
for (i=0 ; i<weeks ; i++)
return randomNums;
}
//Print out the content of an array
void print_array(int *lotteryPtr)
{
printf("Hello");
}
//Returns number of matches between two arrays
int find_matches(int * lotteryPtr, int * randomPtr)
{
}
Update:
#include <stdio.h> //Alows input/output operations
#include <stdlib.h> //Standard utility operations
//Declaring Variables
int year;
char name[15];
char option;
int lotteryPlayer[] = {5,11,15,33,42,43};
int i;
int randomNums[49];
int *lotteryPtr = lotteryPlayer;
int *randomPtr = randomNums;
int weeks = 0;
void print_array(int *lotteryPtr);
int* get_lotto_draw(int *randomPtr);
//Main Method
int main(int argc, char *argv[])
{
start: //Start of program
printf("\n---------------------------");
printf("\nProject: Jackpot Dreams ");
printf("\n---------------------------\n");
printf("\nWhat is your First Name?:> "); //Asks them for their choice
scanf("%s", name); //Reads the input
printf("\nHow Many Years to Sleep?:> "); //Asks them for their choice
scanf("%d", &year); //Reads the input
weeks = year * 52;
printf("\nOk %s, I will play the lottery for %d years!\n",name, year);
sleep(1500);
printf("Sweet Dreams %s, don't let the bed bugs bite", &name);
sleep(1500);
printf(". ");
sleep(1500);
printf(". ");
sleep(1500);
printf(".");
sleep(2000);
printf("%d", get_lotto_draw(*randomPtr));
system("PAUSE");
}
//Returns an array of six random lottery numbers 1-49
int* get_lotto_draw(int *randomPtr)
{
for (i=0 ; i<weeks ; i++)
return randomNums;
}
//Print out the content of an array
void print_array(int *lotteryPtr)
{
printf("Hello");
}
//Returns number of matches between two arrays
int find_matches(int * lotteryPtr, int * randomPtr)
{
}
Borrowing mostly from the comments, there are a few problems with your code.
int weeks = year * 52; results in an error because year hasn't been initialized. Change it to int weeks = 0;, and then put weeks = year * 52 at the beginning of your main function.
You don't need the start: label at the beginning of your program, unless for some reason you want to go back there using a goto, which is usually considered bad practice.
printf("%d", get_lotto_draw); prints the address of get_lotto_draw as a decimal ("%d"), you need to make it get_lotto_draw(args) to get the return value of get_lotto_draw.
system("PAUSE"), runs the command PAUSE on the shell. I don't know if this will pause the current program, but if you don't want the program to exit, a loop will do instead.
while (1) {}
Your implementation of get_lotto_draw doesn't do what you think it does. What you are doing now is just returning randomNums, what you want to do is generate a random number between 1 and 49. To do this you should first generate a random number, and mod it by 48 and add one. This will get you a random number between 1 and 49. srand(time(NULL)); int r = rand(); will generate a random number, and r %= 48; r += 1; will mod it by 48 and add one. You can then do this for each iteration of that for loop, and create an array with the values. The array that you will return will have to be malloc'd.
int get_lotto_draw() {
srand(time(NULL));
int* rv = malloc(sizeof(int) * 6);
for (int i = 0; i < 6; i++) {
rv[i] = (rand() % 48) + 1;
}
return rv;
}
Your find_matches function is also unimplemented. Simply iterating through the arrays to find matches should suffice.
int find_matches(int* a, int* b) {
int matches = 0;
for (int i = 0; i < 6; i++) {
if (a[i] == b[i]) {
matches++;
}
}
return matches;
}
Lastly, for your print_array function, you again just need to iterate through the list of lottery numbers, and print each one.
void print_array(int* arr) {
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("%d", arr[5]);
printf("\n"); // remove this if you don't want a newline at the end.
}

Expression must have class type error

I'm working on a homework assignment and I've hit a brick wall. I think I have all of the code that I need, I just need to get the program to compile. The object of the assignment is
Create a structure to hold student names and averages. The structure should contain a first name, last name and an integer grade average.
Then:
Write a program that will do the following:
1.) Create an array of pointers to these student structures.
2.) Prompt the user for names and averages.
3.) After you get the student’s information use malloc to provide the memory to store the information.
4.) Place the address of the student, returned by malloc, into the pointer array.
5.) AFTER the user indicates there are no more students:
Search the data entered and find the highest and lowest grade
average.
a)Print the name and grade for the highest grade
b)Print the name and grade for the lowest grade
c)Print the average of all grades entered
Here is my code:
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
#define SIZE 25
int enterStudents (int ePointArray[SIZE]);
void searchData (int *sPointArray, int *sHigh, int *sLow);
int calculateAvg (int, int *avgPointArray);
void printData (int, int *pHigh, int *pLow);
struct student
{
char firstName[20];
char lastName[20];
int average;
};
int main()
{
int pointArray[SIZE], high[3], low[3];
int i = 0, studentCounter, avgGrade;
for (i = 0; i < SIZE; i++)
pointArray[i] = 0;
studentCounter = enterStudents(pointArray);
searchData(pointArray, high, low);
avgGrade = calculateAvg(studentCounter, pointArray);
printData(avgGrade, high, low);
return 0;
}
int enterStudents (int ePointArray[SIZE])
{
char tempFname[20], tempLname[20], yesNo[2] = "y";
int tempAvg, counter = 0;
int *studPtr;
struct student aStud={"\0", "\0", 0};
while( counter < SIZE && strcmp(yesNo, "y")==0)
{
printf(" Enter first name: ");
scanf("%s", tempFname);
printf(" Enter last name: ");
scanf("%s", tempLname);
printf(" Enter grade average:");
scanf("%d", tempAvg);
strcpy(aStud.firstName, tempFname);
strcpy(aStud.lastName, tempLname);
aStud.average = tempAvg;
studPtr = malloc(sizeof(struct student));
ePointArray[counter] = *studPtr;
counter++;
printf("/n");
printf(" Do you have more students? yes or no:");
scanf("%s", yesNo);
}
return counter;
}
void searchData (int sPointArray[SIZE], int sHigh[3], int sLow[3])
{
int searchCounter = 0;
while( searchCounter = 0)
{
if( *sPointArray[searchCounter].average > *sPointArray[searchCounter+1].average)
{
sHigh[0] = &sPointArray[searchCounter].firstName;
sHigh[1] = &sPointArray[searchCounter].lastName;
sHigh[2] = &sPointArray[searchCounter].average;
}
if( *sPointArray[searchCounter].average < *sPointArray[searchCounter+1].average)
{
sLow[0] = &sPointArray[searchCounter].firstName;
sLow[1] = &sPointArray[searchCounter].lastName;
sLow[3] = &sPointArray[searchCounter].average;
}
searchCounter++;
}
}
int calculateAvg( int totalStudents, int avgPointArray[SIZE])
{
int sum = 0;
int avgCounter;
double overallAvg;
for( avgCounter = 0; avgCounter < totalStudents; avgCounter++)
sum = sum + *avgPointArray[avgCounter].average;
overallAvg = sum/totalStudents;
return overallAvg;
}
void printData (int pAverage, int pHigh[3], int pLow[3])
{
printf(" Highest Grade: %s %s %d", pHigh[0], pHigh[1], pHigh[3]);
printf("/n");
printf(" Lowest Grade: %s %s %d", pLow[0], pLow[2], pLow[3]);
printf("/n");
printf(" Average Grade: %d",pAverage);
}
The main chunk of problems come from the searchData function. In the if statements, every occurrence of *sPointArray and &sPointArray is underlined in red and the error reads
"Error: expression must have class type"
The same thing also happens in the calculateAvg function with *avgPointArray in the for loop. I know that the error is a fairly common problem for noobie C programmers (i.e myself) and that it generally has to do with writing the code as a function instead of a statement or something like that, but I can't for the life of me find where I have went wrong. Any help would be highly appreciated. I've been working at this for so long my vision is blurring.
Also, for anyone who solves this in like two seconds and wants proof that I'm a true idiot, there is an error in the enterStudents function where it says StudPtr = malloc(sizeof...). The error shows under the assignment symbol and says
"Error: a value of type "void*" cannot be assigned to an entity of type "int*".
I understand this concept in theory, but some advice for how to fix it would be highly appreciated.
Thank you in advance for any help.
You declare the sPointArray as an array of integers, but use it as an array of structures.

Resources