I was tasked with inputting student information based on a given struct, where each field of information is to be typed in one line, separated by a space, then the student id is sorted incrementally, and then print out the information, each student on a new line. The problem is while I thought my code was good, the print part keeps giving fractured results and overall just not printing out the correct values. Where should I fix this?
Here's my code:
#include <stdio.h>
typedef struct
{
char id[8];
int year;
}student;
int main() {
student std[100];
int i, j, num, tmp;
printf("So sinh vien:\n");
scanf("%d", &num);
printf("Nhap thong tin sinh vien:\n");
for(i=0; i <= num; i++)
{
scanf("%c %d\n", &std[i].id, &std[i].year);
}
for(i=0; i < num; i++)
{
for (j=1; j< num; j++)
{
if (std[i].id > std[j].id)
{
tmp = *std[i].id
*std[i].id = *std[j].id;
*std[j].id = tmp;
}
}
}
for(i=0; i < num; i++)
{
printf("%c ", std[i].id);
printf("%d\n", std[i].year);
}
return 0;
}
My output is
So sinh vien:
3
Nhap thong tin sinh vien:
12324521 2003
12341552 2002
12357263 2001
Σ 12324521
≡ 3
ⁿ 2341552
Check the return value of scanf() otherwise you may be operating on uninitialized variables.
Check that num less than the 100 records you allocated for student, or even better use a vla along with a check to avoid large input from smashing the stack.
You input num then read num+1 records but later you only print num records.
As you read a character with "%c" the first input with be the \n from the previous scanf().
The struct contains a char id[8] but you only read a single character into it. Read a string instead.
In sort you use > to compare the first letter of id. You probably want to use strcmp() to compare strings.
In sort section you use a int tmp for storing a character of id (which is ok) but then you write an int which is no good.
In sort you only swap the ids. You probably want to swap the entire record not just the ids.
It seems to be an exchange sort. Use a function, and also at least for me the algorithm didn't work as the inner loop variable should start at j=i+1 not 1.
In your print char id[8] as a single char instead of string.
Moved print functionality to a function. This allows you, for instance, to print the students before and after the sort() during debugging.
Minimizing scope of variables (i and j are now loop local, tmp is only used in the swap() function). This makes code easier to reason about.
#include <stdio.h>
#include <string.h>
#define ID_LEN 7
#define str(s) str2(s)
#define str2(s) #s
typedef struct {
char id[ID_LEN+1];
int year;
} student;
void swap(student *a, student *b) {
student tmp = *a;
*a = *b;
*b = tmp;
}
void print(size_t num, student std[num]) {
for(size_t i=0; i < num; i++)
printf("%s %d\n", std[i].id, std[i].year);
}
// exchange sort
void sort(size_t num, student std[num]) {
for(size_t i=0; i < num - 1; i++)
for (size_t j=i+1; j < num ; j++)
if(strcmp(std[i].id, std[j].id) > 0)
swap(&std[i], &std[j]);
}
int main() {
printf("So sinh vien:\n");
size_t num;
if(scanf("%zu", &num) != 1) {
printf("scanf() failed\n)");
return 1;
}
if(num > NUM_MAX) {
printf("Too many students\n");
return 1;
}
student std[num];
printf("Nhap thong tin sinh vien:\n");
for(size_t i=0; i < num; i++)
if(scanf("%" str(ID_LEN) "s %d", std[i].id, &std[i].year) != 2) {
printf("scanf() failed\n");
return 1;
}
sort(num, std);
print(num, std);
}
and here is an example run:
So sinh vien:
3
Nhap thong tin sinh vien:
aaa 1
zzz 2
bbb 3
aaa 1
bbb 3
zzz 2
printf("%c ", std[i].id);
should be
printf("%s ", std[i].id);
%c means a single char.
Related
in this program I try to sort customer savings descendingly. And I've tried to compile the code. And I'm still not to understand about pointer. There is an error with message "Assignment to expression with array type error". The target output of this program is tend to be the sorted customers(with their names, and account numbers). I've search in the internet about that error. But I still don't get the solution. Can someone help me to solve the error? Thanks.
#include <stdio.h>
#include <stdlib.h>
struct Data
{
long long int Savings[100], AccNo[100];
char Name[100];
};
int main ()
{
struct Data *ptr;
int n, i, j, swap = 1, x, y;
long long int max, min, temp;
printf ("Enter number of customer(s) : ");
scanf ("%d", &n);
ptr = (struct Data *) malloc (n * sizeof (struct Data));
for (i = 0; i < n; i++)
{
printf ("Enter customer %d", i + 1);
printf ("\nName : ");
getchar ();
scanf ("%[^\n]s", &(ptr + i)->Name);
printf ("Savings : ");
scanf ("%d", &(ptr + i)->Savings);
printf ("Account Number : ");
scanf ("%d", &(ptr + i)->AccNo);
printf ("\n");
}
//Sorting bubblesort
for (x = 0; x < n; x++)
{
for (y = 0; y < (n - x - 1); y++)
{
if ((ptr + y)->Savings > (ptr + y + 1)->Savings)
{
temp = (ptr + y)->Savings;
(ptr + y)->Savings = (ptr + y + 1)->Savings;
(ptr + y + 1)->Savings = temp;
}
}
}
//Print sorted
printf ("\n Sorted customers are (:\n");
for (i = 0; i < n; ++i)
{
printf ("%s\n", (ptr + i)->Name);
printf ("%d\n", (ptr + i)->Savings);
}
free (ptr);
return 0;
}
You need to compile your code with warnings enabled, the will guide
you through debugging step by step. Try to eliminate one, and
compile again. In GCC for example, you would use -Wall flag.
The numerical fields of your struct should be just numbers, not
arrays. Moreover, having their type as long long int seems a bit
too much, but I leave that on you.
Having (ptr + y)->Savings to access the y-th element of an array
of structs and the its field names Savings is technically correct,
but it's much more cleaner (thus increases readability and
maintainability) to write ptr[y].Savings. That is a general rule,
applying to the rest of your code.
I believe the above led you to make two syntactical errors when you
were reading the numerical data of the customers with scanf(),
since you know that an integer in general needs the & operator. If
you had used the clean approach from the start, you wouldn't made
those, I believe.
For long long int use the %lld format specifier, not just %d.
In Bubblesort, when you find elements that need to be swapped, then
swap the whole elements, not just their Savingss. I recommend
creating a function to do that.
scanf("%[^\n]s" doesn't make much sense, I would change it to
scanf("%99s", where 99 is the maximum size of your string, minus
one. Read more in the 2nd paragraph in scanf(“%[^\n]s”,a) question.
Putting everything together, we get:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Data {
long long int Savings, AccNo; // these should be numbers, not arrays
char Name[100];
};
void swap(struct Data* a, struct Data* b) {
struct Data tmp;
tmp.Savings = a->Savings;
tmp.AccNo = a->AccNo;
strcpy(tmp.Name, a->Name);
a->Savings = b->Savings;
a->AccNo = b->AccNo;
strcpy(a->Name, b->Name);
b->Savings = tmp.Savings;
b->AccNo = tmp.AccNo;
strcpy(b->Name, tmp.Name);
}
int main() {
struct Data *ptr;
int n, i, x, y;
printf("Enter number of customer(s) : ");
scanf("%d", &n);
ptr = malloc (n * sizeof(struct Data)); // do not cast malloc
for(i=0; i<n; i++) {
printf("Enter customer %d", i+1);
printf("\nName : ");
getchar();
scanf("%99s", ptr[i].Name); // ptr is a pointer, but now you want to actually use it as an array, so use '.'
printf("Savings : ");
scanf("%lld", &ptr[i].Savings); // needs &, just like you did for 'n'. USe `%lld' for long lont int as the format specifier.
printf("Account Number : ");
scanf("%lld", &ptr[i].AccNo); // needs &, just like you did for 'n'. USe `%lld' for long lont int as the format specifier.
printf("\n");
}
//Sorting bubblesort
for (x = 0; x < n; x++)
{
for (y = 0; y < n - x - 1; y++) // you don't need paranetheses in the stop condition
{
if (ptr[y].Savings > ptr[y + 1].Savings)
{
swap(&ptr[y], &ptr[y + 1]); // swap the whole element, not just its savings
}
}
}
//Print sorted
printf("\nSorted customers are:\n");
for(i=0; i<n; ++i)
{
printf("%s\n", (ptr+i)->Name);
printf("%lld\n", (ptr+i)->Savings);
}
free(ptr);
return 0;
}
Output (with relevant input):
Sorted customers are:
George
1
Babis
3
Theodor
20
PS: Do I cast the result of malloc? No!
I have to declare a vector with the "struct" type which, for every n students, it creates a value for the group that student belongs to (which is like a counter), their names and their grades.
The program has to output the name of the students with the highest grade found in these groups. I have to allocate the vector on the heap (I only know the theoretical explanation for heap, but I have no idea how to apply it) and I have to go through the vector using pointers.
For example if I give n the value 4, there will be 4 students and the program will output the maximum grade together with their names as shown here.
This will output Ana 10 and Eva 10.
I gave it a try, but I have no idea how to expand it or fix it so I appreciate all the help I can get with explanations if possible on the practical application of heap and pointers in this type of problem.
#include <stdio.h>
#include <stdlib.h>
struct students {
int group;
char name[20];
int grade;
};
int main()
{
int v[100], n, i;
scanf("%d", n);
for (i = 0; i < n; i++) {
v[i].group = i;
scanf("%s", v[i].name);
scanf("%d", v[i].grade);
}
for (i = 0; i < n; i++) {
printf("%d", v[i].group);
printf("%s", v[i].name);
printf("%d", v[i].grade);
}
return 0;
}
Here I was just trying to create the vector, nothing works though..
It appears, int v[100]; is not quite what you want. Remove that.
You can follow either of two ways.
Use a VLA. After scanning the value of n from user, define the array like struct students v[n]; and carry on.
Define a fixed size array, like struct students v[100];, and use the size to limit the loop conditions.
That said,
scanf("%d", n); should be scanf("%d", &n);, as %d expects a pointer to integer type argument for scanf(). Same goes for other cases, too.
scanf("%s", v[i].name); should better be scanf("%19s", v[i].name); to avoid the possibility of buffer overflow by overly-long inputs.
Even though you are asking for the number of students (groups) using scanf, you hardcoded the upper bound of this value using v[100]. So, I passed your input variable n (the number of students) to malloc in order to allocate the space you need for creating an array of n students.
Also, I used qsort to sort the input array v where the last element would be the max value. Here qsort accepts an array of structs and deference the pointers passed to the comp function to calculate the difference of the comparison.
Finally, I printed the sorted array of structs in the last loop.
#include <stdio.h>
#include <stdlib.h>
struct students {
int group;
char name[20];
int grade;
};
int comp(const void *a, const void *b)
{
return ((((struct students *)a)->grade > ((struct students *)b)->grade) -
(((struct students *)a)->grade < ((struct students *)b)->grade));
}
int main()
{
int n;
printf("Enter number of groups: ");
scanf("%d", &n);
printf("\n");
struct students *v = malloc(n * sizeof(struct students));
int i;
for(i = 0; i < n; i++)
{
v[i].group = i;
printf("\nName: ");
scanf("%s", v[i].name);
printf("Grade: ");
scanf("%d", &v[i].grade);
}
qsort(v, n, sizeof(*v), comp);
for(i = 0; i < n; i++)
{
printf("Group %d, Name %s, grade %d\n", v[i].group, v[i].name, v[i].grade);
}
return (0);
}
You need to replace the standalone array v[100], with an array of structs referencing your structure:
struct students v[100];
However, if you want to use malloc to allocate memory on the heap, you will need to do something like this:
struct students *students = malloc(n * sizeof(struct students));
/* Check void* return pointer from malloc(), just to be safe */
if (students == NULL) {
/* Exit program */
}
and free the requested memory from malloc() at the end, like this:
free(students);
students = NULL;
Additionally, adding to #Sourav Ghosh's answer, it is also good to check the return value of scanf(), especially when dealing with integers.
Instead of simply:
scanf("%d", &n);
A more safe way is this:
if (scanf("%d", &n) != 1) {
/* Exit program */
}
With all this said, your program could look something like this:
#include <stdio.h>
#include <stdlib.h>
#define NAMESTRLEN 20
typedef struct { /* you can use typedef to avoid writing 'struct student' everywhere */
int group;
char name[NAMESTRLEN+1];
int grade;
} student_t;
int
main(void) {
int n, i;
printf("Enter number of students: ");
if (scanf("%d", &n) != 1) {
printf("Invalid input.\n");
exit(EXIT_FAILURE);
}
student_t *students = malloc(n * sizeof(*students));
if (!students) {
printf("Cannot allocate memory for %d structs.\n", n);
exit(EXIT_FAILURE);
}
for (i = 0; i < n; i++) {
students[i].group = i;
printf("Enter student name: ");
scanf("%20s", students[i].name);
printf("Enter students grade: ");
if (scanf("%d", &(students[i].grade)) != 1) {
printf("Invalid grade entered.\n");
exit(EXIT_FAILURE);
}
}
printf("\nStudent Information:\n");
for (i = 0; i < n; i++) {
printf("Group: %d Name: %s Grade: %d\n",
students[i].group,
students[i].name,
students[i].grade);
}
free(students);
students = NULL;
return 0;
}
Hello everyone,
I decided some time ago to write my own version of Minesweepers as some practice and I did it. The game ran perfectly, but after deciding to add a "Choose difficulty" option the window freezes and I get an error message, saying that the program does not respond. Also the line 0xC0000005 appeares. I have tryed many, many things: moving code from main() to a seperate function(now all in int playGame()), allocating some more memory in the heap, even creating a seperate .c file to store some piece of the code, but nothing worked sofar. I came back to the code after a few weeks, but I still have no clue why it is happening.
Can anyone help me with this? I hope my code is not hard to read. I added some comments explaining what is what. I am still new to C.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "difLvl.c"
int displayFiled(char **field); //prints out the map of the field
int combine(char answer, int answer1); //combines user input and field numeration
int Randomizer(int **mineArray); //generates random mine map
int difficulty();
int playGame();
int main(){
int playGame();
playGame();
system("PAUSE");
return 0;
}
int Randomizer(int **mineArray){
int difficulty();
int i, j;
srand(time(NULL));
int mines;
int placeMine;
int totalMines;
//int difLvl=2;
int difLvl=difficulty();
for(i=0, totalMines=0; i<10; i++){
for(j=0, mines=0; j<10 && mines<difLvl; j++){
placeMine= rand() % 2;
mineArray[i][j] = placeMine;
if(placeMine==1){
++mines;
};
};
totalMines+=mines;
};
return totalMines;
}
int displayFiled(char **field){
int i, j;
printf(" A B C D E F G H I J\n");
printf(" --------------------\n");
for (i=0; i<10; i++){
if (i==9){
printf("%d |", i+1);
}else{
printf("%d |", i+1);
};
for (j=0; j<10; j++){
printf("%c ", field[i][j]);
if (j==9){
printf("\n");
};
};
};
printf("\n");
return 0;
}
int playGame(){
int displayFiled(char **field);
int combine(char answer, int answer1);
int Randomizer(int ** mineArray);
char Y_char; //column as character (a, b, c etc.)
int X; //row
int Y; //Y_char converted to a number
int **mineArray; //stores the map of mines
char **fieldDisplay; //prints out the map of the field
int i, j; //counters
int life=1;
int movePl=0; //no dying on the first move
int globalMines; //number of mines placed
int openedFields=0; //counts the number of fields opened
//int difLvl;
//int difficulty();
//difLvl= difficulty();
/*disabled the trhee lines above while I was trying some solutions*/
/*int difficulty() is now called from int Randomizer()*/
system("cls");
/*Allocates memory to mineArray*/
mineArray= (int*)calloc(10, sizeof(int));
for(i = 0; i < 10; i++){
mineArray[i] = calloc(10, sizeof(int));
};
/*Allocates memory to fieldDisplay*/
fieldDisplay= (int*)calloc(10, sizeof(int));
for(i = 0; i < 10; i++){
fieldDisplay[i] = calloc(10, sizeof(int));
};
/*default look of fields with ?*/
for (i=0; i<10; i++){
for (j=0; j<10; j++){
fieldDisplay[i][j]='?';
};
};
globalMines= Randomizer(mineArray);
while(life==1 && openedFields<(100-globalMines)){
/*for checking purposes only*/
/*for (i=0; i<10; i++){
for (j=0; j<10; j++){
printf("%d ", mineArray[i][j]);
if (j==9){
printf("\n");
};
};
};*/
//printf("\nDifficulty level %d\n", difLvl);
printf("Total number of mines is %d\n\n", globalMines);
printf("\tMove nr. %d\n\n", movePl+1);
displayFiled(fieldDisplay);
printf("Which field do You want to activate?\nType first the letter, space and then the number (A 1, B 10 etc.)\n");
scanf("%c %d", &Y_char, &X);
if (Y_char >= 'A' && Y_char <= 'Z'){
Y = Y_char - 'A';
}else if(Y_char >= 'a' && Y_char <= 'z'){
Y = Y_char - 'a';
};
/*checks if a field is a mine*/
/*X-1 because the player chooses from 1 to 10*/
if (mineArray[X-1][Y]==0 && fieldDisplay[X-1][Y]=='?'){
movePl++;
fieldDisplay[X-1][Y]='0';
openedFields=openedFields+1;
OPEN : if (((X-2)<10) && ((X-2)>=0)){
if (mineArray[X-2][Y]==0 && fieldDisplay[X-2][Y]=='?'){
fieldDisplay[X-2][Y]='0';
openedFields=openedFields+1;
};
};
if ((X<10) && (X>=0)){
if (mineArray[X][Y]==0 && fieldDisplay[X][Y]=='?'){
fieldDisplay[X][Y]='0';
openedFields=openedFields+1;
};
};
if (((Y+1)<10) && ((Y+1)>=0)){
if (mineArray[X-1][Y+1]==0 && fieldDisplay[X-1][Y+1]=='?'){
fieldDisplay[X-1][Y+1]='0';
openedFields=openedFields+1;
};
};
if (((Y-1)<10) && ((Y-1)>=0)){
if (mineArray[X-1][Y-1]==0 && fieldDisplay[X-1][Y-1]=='?'){
fieldDisplay[X-1][Y-1]='0';
openedFields=openedFields+1;
};
};
system("cls"); //clears console screen
}else if (mineArray[X-1][Y]==0 && fieldDisplay[X-1][Y]=='0'){
system("cls");
printf("You can't choose an already opened field!\n\n");
}else if(mineArray[X-1][Y]==1 && movePl==0){
/*only activates on the first turn if players hits mine*/
movePl++;
mineArray[X-1][Y]= 0;
fieldDisplay[X-1][Y]='0';
globalMines=globalMines-1;
goto OPEN;
system("cls");
}else{
system("cls");
printf("YOU DIED ! YOU DIED ! YOU DIED !\n\n");
printf("Moves successfully made: %d\n\n", movePl-1);
fieldDisplay[X-1][Y]='1';
displayFiled(fieldDisplay);
--life;
};
};
if(openedFields==(100-globalMines)){
printf("Congratulations! You won the game!\n\n");
displayFiled(fieldDisplay);
};
for(i = 0; i < 10; i++){
free(mineArray[i]);
};
free(mineArray);
for(i = 0; i < 10; i++){
free(fieldDisplay[i]);
};
free(fieldDisplay);
return 0;
}
The difLvl.c file:
#include <stdio.h>
#include <stdlib.h>
int difficulty(){
int difLvl;
while(1){
printf("Please choose a difficulty level:\n");
printf("Easy-1\nNormal-2\nNightmare-3\n");
printf("Your answer: ");
scanf(" %d", &difLvl);
if(difLvl>=1 && difLvl<=3){
break;
}else{
system("cls");
continue;
};
};
system("cls");
return difLvl;
}
I created it, because I thought that maybe main() had too many code in it and that maybe that was why the difficulty option wasnt working right.
EDIT
After the user is promped to enter the difficulty level, the mine map is created, but after choosing a filed, the program crashes.
SOLVED
scanf("%c %d", &Y_char, &X);
changed to
scanf(" %c %d", &Y_char, &X);
First, you don't allocate your two-dimensional fields correctly. The "outer" field must hold int *, not just int:
mineArray = calloc(10, sizeof(*mineArray));
for (i = 0; i < 10; i++) {
mineArray[i] = calloc(10, sizeof(*mineArray[i]));
}
Another potential source of the segmentation fault is that Y might end up uninitialised and therefore with a garbage value. The cause is the scanf:
scanf("%c %d", &Y_char, &X);
Most scanf formats skip white space before the conversion, but %c doesn't. It is very likely that you read the newline character as the char for %c when you expect to read a letter. Because the new-line character is white space, you can hot-fix the by placing a space before the %c? format:
scanf(" %c %d", &Y_char, &X);
(I say hot-fix, because it isn't a good solution. scanf doesn't treat new-line characters specially; they are just space. A better solution might be to read a line first with fgets and then scan that with sscanf. At least you can treat each line as frash input. (And your input really should ensure that bad input is ignored.)
Lastly, it is strange that you include a *.c file. If you want to spread ypur project over various files, which is basically a good idea, you should write a header file for each *.c, which has the file's interface. Include the header files in other *.c files; compile the *.c files into objects separately and then link them. This process is usually controlled by Makefiles or Projects.
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.
}
I'm writing a program to alphabetize inputted names and ages. The ages are inputted separately, so I know I need to use an array of pointers to tie the ages to the array of names but I can't quite figure out how to go about doing it. Any ideas?
So far, my program only alphabetizes the names.
/* program to alphabetize a list of inputted names and ages */
#include <stdio.h>
#define MAXPEOPLE 50
#define STRSIZE
int alpha_first(char *list[], int min_sub, int max_sub);
void sort_str(char *list[], int n);
int main(void)
{
char people[MAXPEOPLE][STRSIZE];
char *alpha[MAXPEOPLE];
int num_people, i;
char one_char;
printf("Enter number of people (0...%d)\n> ", MAXPEOPLE);
scanf("%d", &num_people);
do
scanf("%c", &one_char);
while (one_char != '\n');
printf("Enter name %d (lastname, firstname): ", );
printf("Enter age %d: ", );
for (i = 0; i < num_people; ++i)
gets(people[i]);
for (i = 0; i < num_people; ++i)
alpha[i] = people[i];
sort_str(alpha, num_people);
printf("\n\n%-30s5c%-30s\n\n", "Original List", ' ', "Alphabetized List");
for (i = 0; i < num_people; ++i)
printf("-30s%5c%-30s\n", people[i], ' ', alpha[i]);
return(0);
}
int alpha_first(char *list[], int min_sub, int max_sub)
{
int first, i;
first = min_sub;
for (i = min_sub + 1; i <= max_sub; ++i)
if (strcmp(list[i], list[first]) < 0)
first = i;
return (first);
}
void sort_str(char *list[], int n)
{
int fill, index_of_min;
char *temp;
for (fill = 0; fill < n - 1; ++fill){
index_of_min = alpha_first(list, fill, n - 1);
if(index_of_min != fill){
temp = list[index_of_min];
list[index_of_min] = list[fill];
list[fill] = temp;
}
}
}
Most of your printfs are syntax errors, as in
printf("Enter name %d (lastname, firstname): ", );
printf("Enter age %d: ", );
or bomb right away, since you pass an int (' ') as a pointer:
printf("\n\n%-30s5c%-30s\n\n", "Original List", ' ', "Alphabetized List");
As a first step, get all your %s right and show us what you really compiled, not some random garbage. And crank your compiler's warning level to the maximum, you need it! What is
#define STRSIZE
supposed to mean when STRSIZE is used as an arary dimension? You have a serious cut&paste problem, it would appear.
Creating a struct would probably be easier: i.e
struct person {
char name[STRSIZE];
int age;
}
Otherwise, if you must do it the way you're trying, just create an extra array of the indexes. When you move a name, you also move the index on the array... when you're done sorting names, just sort the ages to match the indexes.