Realloc to structure in c - c

i have a problem with my realloc in the func add order its crash every time
someone can help me here
typedef struct
{
char carname[30]; //car names
int price; //the price of the car
}Vehicle;
typedef struct {
int number; // מספר הזמנה
char *name; // שם המזמין
char ID[10]; // מספר זהות שלו
int number_vehicles; // מספר הרכבים בהזמנה
Vehicle * list;
int sum_order;
}Order;
Order * add_orders(Order * firma, int * ordersize)// adding one more order
{
int i, j;
char temp[80];
int newstart; // because we need to add one more order we need new start and it will be the old size of the number of orders
newstart = *ordersize; //we just did it
(*ordersize)++; // now we have new size +1 for the one more order
for (i = newstart; i < *ordersize; i++) //same as the input function but this one start and finish from the new start and finish
{
printf("enter the ID of order number: %d\n", i + 1);
scanf("%d", &firma[i].number);
while (getchar() != '\n');
printf("enter the name of the client:\n");
gets(temp);
firma[i].name = (char*)malloc(strlen(temp) + 1 * sizeof(char));
if (!firma[i].name)
{
printf("error\n");
return 0;
}
strcpy(firma[i].name, temp);
printf("enter the ID of client (length can only be 10):\n");
gets(firma[i].ID);
printf("enter how many vehicles you want in this order\n");
scanf("%d", &firma[i].number_vehicles);
firma[i].list = (Vehicle*)malloc(firma[i].number_vehicles * sizeof(Vehicle));
if (!firma[i].list)
{
printf("error\n");
return 0;
}
for (j = 0; j < firma[i].number_vehicles; j++)
{
while (getchar() != '\n');
printf("enter the name of the vehicle number %d (only 30 chars):\n", j + 1);
gets(firma[i].list[j].carname);
printf("enter the price of the vehicle\n");
scanf("%d", &firma[i].list[j].price);
}
}
firma = (Order*)realloc(firma, (*ordersize * sizeof(Order))); //after we added the new order we do realloce for the new size for the struct
if (!firma)//if failed
{
printf("error\n");
return 0;
}
}
int main()
{
int i, j;
char temp[80];
char *str = NULL;
int num, x, y;
int number;
int ordersize;
int exit1 = 0;
int exit2 = 0;
int exit3 = 0;
int flag = 0;
int choose;
Order *data = NULL; //pointer to the struct Order
printf("\nenter how many orders you want\n");
scanf("%d", &ordersize); //enter size of orders
data = (Order*)malloc(ordersize * sizeof(Order));//we allocte memory for the struct Order with pointer data
add_orders(data, &ordersize); //send it
return 0;
}
i have a problem with my realloc in the func add order its crash every time
someone can help me here
i have a problem with my realloc in the func add order its crash every time
someone can help me here
i have a problem with my realloc in the func add order its crash every time
someone can help me here

You access out of bound for firma.
data = (Order*)malloc(ordersize * sizeof(Order));//we allocte memory for the struct Order with pointer data
add_orders(data, &ordersize); //send it
As you allocated memory of size orderSize and you access firma[newstart].
newstart = *ordersize; //we just did it
(*ordersize)++; // now we have new size +1 for the one more order
for (i = newstart; i < *ordersize; i++) //same as the input function but this one start and finish from the new start and finish
{
printf("enter the ID of order number: %d\n", i + 1);
scanf("%d", &firma[i].number);
while (getchar() != '\n');
.....
}
Thus first allocate more memory and access.
newstart = *ordersize; //we just did it
(*ordersize)++; // now we have new size +1 for the one more order
firma = (Order*)realloc(firma, (*ordersize * sizeof(Order))); //after we added the new order we do realloce for the new size for the struct
if (!firma)//if failed
{
printf("error\n");
return 0;
}
for (i = newstart; i < *ordersize; i++) //same as the input function but this one start and finish from the new start and finish
{
printf("enter the ID of order number: %d\n", i + 1);
scanf("%d", &firma[i].number);
while (getchar() != '\n');
.....
}
Note:: firma is local variable and allocating memory using realloc
in addOrder function has no effect on data variable in main
function. You may need to pass data using reference or return
updated value from function and assign it to data.

Related

Issues with printing structs in C

I'm incredibly new to this and have a school assignment I have to write a gradebook program that uses a custom struct to hold student IDs and grades. I have been trying unsuccessfully for days to figure out why it will not print properly, or when it does print (after a lot of shifting things around) it only prints the second set of input.
The gradebook.h section is the custom structure.
// gradebook.h
struct gradeID
{
int id;
char grades[25];
};
// Gradebook.h is a header file to define
// a global structure.
#include "gradebook.h"
#include <stdio.h>
#include <stdlib.h>
void sort(struct gradeID *, int);
int main(void)
{
// Variables and structure definitions
int ctr;
char contInput;
int i;
struct gradeID grade;
struct gradeID *identifier;
int *temps;
// Allocates 10 integers worth of memory for the program to use.
// If there is not enough memory, the program will print an error
// statement and terminate the program.
temps = (int *) malloc(10 * sizeof(int));
if (temps == 0)
{
printf("Not enough memory!\n");
exit(1);
}
// Prints basic instructions for the program
printf("\t\tGradebook Recorder\n");
printf("Input student IDs and grades.\n");
printf("These will be sorted by ID and printed.\n");
/* Creates a for loop that will continue until the program
hits the designated number of array elements. For the sake
of expediency, I have set this amount to 10, but it can be
changed as necessary.*/
for(i = 0; i < 10; i++)
{
printf("Input student ID:\n");
scanf(" %d", &grade.id);
printf("Input grade:\n");
scanf(" %s", grade.grades);
// This allows early exit of the program
printf("Do you have more grades to enter?\n");
printf("Y/N\n");
scanf(" %c", &contInput);
if(contInput == 'N' || contInput == 'n')
{
printf("Finalizing and printing input-\n\n");
break;
}
ctr++;
}
printf("Grades Sorted by Student ID:\n\n");
printf("\tStudent ID: Student Grade: \n");
for(i = 0; i < ctr; i++)
{
printf("\t%d", grade.id );
printf("\t%s", grade.grades);
}
identifier[i] = grade;
return(0);
free(temps);
}
void sort(struct gradeID identifier[], int counter)
{
int inner;
int outer;
struct gradeID temp;
// Loops for sorting
for(outer = 0; outer < counter - 1; ++outer)
{
for(inner = outer + 1; inner < counter; ++inner)
{
if(identifier[inner].id < identifier[outer].id)
{
temp = identifier[inner];
identifier[inner] = identifier[outer];
identifier[outer] = temp;
}
}
}
return;
}
The pointer identifier is uninitialized
struct gradeID *identifier;
So this statement
identifier[i] = grade;
independent on the value of i invokes undefined behavior.
In this for loop
for(i = 0; i < 10; i++)
{
printf("Input student ID:\n");
scanf(" %d", &grade.id);
printf("Input grade:\n");
scanf(" %s", grade.grades);
// This allows early exit of the program
printf("Do you have more grades to enter?\n");
printf("Y/N\n");
scanf(" %c", &contInput);
if(contInput == 'N' || contInput == 'n')
{
printf("Finalizing and printing input-\n\n");
break;
}
ctr++;
}
you are entering new data in the same object grade of the structure type. So the new data overrides the previous data stored in the object.
Moreover the variable ctr was not initialized
int ctr;
So this statement in the above for loop
ctr++;
also invokes undefined behavior.
The variable temps that points to a dynamically allocated array
temps = (int *) malloc(10 * sizeof(int));
is not used.
This statement
free(temps);
never gets the control because before it there is the return statement
return(0);
free(temps);
What you need is to define an array of the type struct gradeID as for example
struct gradeID grades[10];
and fill it with values.

How to delete a value in a struct?

I am trying to delete a "user" from the struct on my code.
For example, this is the struct I have:
struct clients {
char name[30];
int year;
float amount;
};
And this is the two outputs I have:
Name: Victor
Birth Year: 1998
Amount: 1000.00
Name: John
Birth Year: 1996
Amount: 1500.00
What I want to do is to delete John and all his information from my struct.
I am trying to learn dynamic memmory allocation, so I used this command:
clt = (struct clients*) malloc(n * sizeof(struct clients));
In my case I wish to write a command on case 3 that delete john from the struct, but I really can't figure out how to do that, I guess maybe using realloc? But I didn't even get close to write something it would work.
Here is my entire code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct clients {
char name[30];
int year;
float amount;
};
int main() {
struct clients *clt;
int option, n, d = 0;
char name[30];
printf("Welcome, Choose an option to begin:");
do {
printf("\n1 - Create a new list;\n");
printf("2 - Find a person in the list;\n");
printf("3 - Delete a person from the list.\n");
printf("4 - End the program.\n");
scanf("%d", &option);
switch (option) {
case 1:
printf("\nType how many clients you want to register:");
scanf("%d", &n);
// allocating memory for n numbers of struct person
clt = (struct clients*) malloc(n * sizeof(struct clients));
for (int i = 0; i < n; i++) {
printf("Type the name and the birth year:");
// To access members of 1st struct person,
scanf("%s %d", (clt + i)->name, &(clt + i)->year);
printf("\nType the amount:");
scanf("%f", &(clt + i)->amount);
}
break;
case 2:
printf("Type the name you want to find:");
scanf("%s", name);
for (int i = 0; i < n; i++) {
if (strcmp(&clt[i].name, name) == 0) {
printf("\nThats the name:");
printf("\nName: %s\n", (clt + i)->name);
printf("Birth Year: %d\n", (clt + i)->year);
printf("Amount: %.2f\n", (clt + i)->amount);
d++;
}
}
if (d == 0)
printf("This name doesn't exist\n");
break;
case 3:
break;
case 4:
break;
}
} while (option != 4);
return 0;
}
You need to discard the element from its location in the list by moving the contents in the remainder of the list up , and overwriting the target element.
for(int i = 0; i < n; i++) {
if (strcmp(&clt[i].name, name)==0)
{
printf("\nThats the name:");
printf("\nName: %s\n", (clt+i)->name);
printf("Birth Year: %d\n", (clt+i)->year);
printf("Amount: %.2f\n", (clt+i)->amount);
d++; // This seems to be your sentinel value?
}
if ( 1 == d && i+1 != n ) // if the sentinel is set, but we're not off the end of the list yet
{
memcpy(clt+i, clt+i+1, sizeof( struct clients ));
}
}
n--; // reduce the list length
You could do this in one memmove call if you prefer. As #Neil says in the comments, memmove is tolerant of overlapping source and destination.
if ( 1 == d && i != n-1 ) // if the sentinel is set, but we're not off the end of the list yet
{
memmove(clt+i, clt+i+1, (n-i-1) * sizeof( struct clients ));
break; // break for i
}
You are describing almost a dynamic array such as C++'s std::vector. It is static, but it could be a dynamic array without that much extra work. You could create a container, and split n into the container's capacity and size.
struct clients_array {
size_t size, capacity;
struct clients *data;
};
Instead of having multiple pointers, one could create a struct clients_array for each list. Sample code to deal with the struct clients_array.
#include <inttypes.h>
#include <assert.h>
#include <errno.h>
/** `a` constructor with `n` spots. Returns true or false depending on whether
it could be constructed. */
static int clients_array_reserve(struct clients_array *const a,
const size_t n) {
assert(a && n);
if(n > SIZE_MAX / sizeof *a->data) return errno = ERANGE, 0;
if(!(a->data = malloc(sizeof *a->data * n))) return 0;
a->capacity = n;
a->size = 0;
return 1;
}
/** `a` destructor; call this when `a` has been successfully constructed. */
static void clients_array_(struct clients_array *const a)
{ if(a) { free(a->data); a->data = 0; a->capacity = a->size = 0; } }
/** Extract a new uninitialized entry out of constructed `a`. Returns null if
there is no more space. */
static struct clients *clients_array_new(struct clients_array *const a) {
assert(a);
return a->capacity > a->size ? a->data + a->size++ : 0;
}
/** Remove index `rm` from `a`. */
static void clients_array_delete(struct clients_array *const a,
const size_t rm) {
assert(a && rm < a->size);
memmove(a->data + rm, a->data + rm + 1,
sizeof *a->data * (a->size - rm - 1));
a->size--;
}
Then one can have different, independent arrays at once. If you want to update the code, say to allow realloc to increase the size of the object, you only need to modify the container.

seg fault in c with pointers

I have two fucntions that prompt the user to print ingredients names for pizza and print them out. But whenever I'm trying to print out the available ingredients, I get a seg fault.
And when I prompt to enter ingredients, if I say we have 3 available ingredients today, I can only type 2 in (as shown in the output picture)
int get_ingredients(char** ingredients,int* num_ingredients) {
char **ingredients_array = NULL; /*this is an array of pointers points to single ingredient in get_item*/
int temp,i,j;
ingredients = &ingredients_array; /*ingredients is a pointer points to the array of pointers*/
temp = *num_ingredients;
printf("How many available pizza ingredients do we have today? ");
scanf("%d",&temp);
ingredients_array = (char**)calloc(temp, sizeof(char*));
i = 0;
printf("Enter the ingredients one to a line: \n");
while (i < temp){
*(ingredients_array+i) = get_item();
i++;
}
i = 0;
printf("Available ingredients today are: \n");
while(i < temp) {
j = i+1;
printf("%d",j);
print(". ");
printf("%s", **(ingredients_array+i));
i++;
}
*num_ingredients = temp;
return EXIT_SUCCESS;
}
char* get_item(){
int i,a;
char *each_ingredient= (char*)malloc(61*sizeof(char)); /*points to each input*/
a = getchar();
i = 0;
while (a != EOF && (char)a != '\n'){
*(each_ingredient+i)= (char)a;
a = getchar();
i++;
}
*(each_ingredient+i) = '\n';
return each_ingredient;
}
This is the output
There are many issues with your get_ingredients question.
The first issue that I noticed is that you changed the pointer of the parameter ingredients, you changed it to the pointer get_ingredients which was set to NULL. So accessing the data from ingredients pointer from now on will get you a segmentation fault, for trying to access an illegal address.
int get_ingredients(char** ingredients,int* num_ingredients) {
char **ingredients_array = NULL; /*this is an array of pointers points to single ingredient in get_item*/
int temp,i,j;
//ingredients pointer is lost forever and set to the address of the pointer of ingredients_array
ingredients = &ingredients_array; /*ingredients is a pointer points to the array of pointers*/
Now the second issue is more of an optimization thing. You set a variable, and then you changed it on the scanf, making the useless to set it to some value initially.
//Temp is set to num_ingredients, but this is of no use,becuase this value is never used and is overwritten by scanf("%d",&temp);
temp = *num_ingredients;
printf("How many available pizza ingredients do we have today? ");
scanf("%d",&temp);
Should allocate pointer of a pointer to char.
ingredients_array = (char**)calloc(temp, sizeof(char*));
Changes
ingredients_array = (char**)calloc(temp, sizeof(char**));
The while loops can be replaced with a for a loop. Which a more appropriate type of loop for this case.
//This can write it better with a for loop
i = 0;
printf("Enter the ingredients one to a line: \n");
while (i < temp){
*(ingredients_array+i) = get_item();
i++;
}
i = 0;
printf("Available ingredients today are: \n");
//Use for loop intead, because it more appropiate for this case
while(i < temp) {
//better to use i+1 instead of j, simply things
j = i+1;
//These two printf can be on the same line
printf("%d",j);
printf(". ");
//Allocation error?
printf("%s", **(ingredients_array+i));
i++;
}
Using a for loop instead, getting user input from standard function, and using less confusing indexing.
printf("Enter the ingredients one to a line: \n");
//Using for loop
for(int i = 0;i < temp;i++)
{
char ptr[80]; //Store user input
scanf("%s", ptr); //Get user input
ingredients_array[i] = strdup(ptr); //strdup is to make a another string with the same contents
}
printf("Available ingredients today are: \n");
for(int i = 0; i < temp;i++)
{
//These two printf can be on the same line
printf("%d",i+1);
print(". ");
//Allocation error?
printf("%s\n", ingredients_array[i]);
}
*num_ingredients lost its original pointer earlier, so this serves no use.
//This cannot be used because now points to ingredients_array and not to num_ingredients
*num_ingredients = temp;
Now the code with all those changes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int get_ingredients(char** ingredients,int* num_ingredients) {
char **ingredients_array = NULL; /*this is an array of pointers points to single ingredient in get_item*/
int temp;
printf("How many available pizza ingredients do we have today? ");
scanf("%d",&temp);
ingredients_array = (char**)calloc(temp, sizeof(char**));
printf("Enter the ingredients one to a line: \n");
//Using for loop
for(int i = 0;i < temp;i++)
{
char ptr[80]; //Store user input
scanf("%s", ptr); //Get user input
ingredients_array[i] = strdup(ptr); //strdup is to make a another string with the same contents
}
printf("Available ingredients today are: \n");
for(int i = 0; i < temp;i++)
{
printf("%d. ",i+1);
printf("%s\n", ingredients_array[i]);
}
*num_ingredients = temp;
return EXIT_SUCCESS;
}
int main()
{
char** ingredients;
int a;
int foo = get_ingredients(ingredients, &a);
return 0;
}
Output
How many available pizza ingredients do we have today? 4
Enter the ingredients one to a line:
meat
MEAT
mEaT
no_salas
Available ingredients today are:
1. meat
2. MEAT
3. mEaT
4. no_salad

Copying variables for an array to another array with the array being a struct with chars

First off Ill show you how I'm defining struct StudentRecord
typedef struct{
char SN[10];
char lname[20];
float GPA;
}StudentRecord;
Now the point of this is to read in information from a .dat file which this program does successfully but when I go to save the array that I have made (more on this below) it give me a very weird output this code has a 2 global variables
StudentRecord* studentRecordList;
int studentRecordSize;
the studentRecordSize is going to be the first input line from the file, the function for reading the files looks like the following.
void load_records(){
FILE* student_file = fopen("StudentRecordFile.dat", "r");
if(student_file == 0){
perror("cannot open StudentRecordFile.dat in load_records");
}
//free existing student list
if(studentRecordList != 0){
free(studentRecordList);
}
//get number of students in the list
fscanf(student_file, "%d",&studentRecordSize);
//create and load new student list
studentRecordList = (StudentRecord*)malloc(studentRecordSize * sizeof(StudentRecord));
int i;
for(i = 0; i < studentRecordSize;i++){
fscanf(student_file,"%s %s %s %f", studentRecordList[i].SN,studentRecordList[i].fname,studentRecordList[i].lname,&studentRecordList[i].GPA);
}
fclose(student_file);
}
Now from the driver you are given 4 options to 0-exit(also saves to the file), 1-find(just a search through the array), 2-add(add another student to the array), 3-modify, 4-delete.
the function for adding a student to the array is where I'm getting my problem for some reason it is messing up my output file and changing all my GPA variables to 0.000000 and leaving random blank spaces throughout the document. Anyway here is what it looks like.
void add_record(){
char fname[20];
char lname[20];
char SN[10];
float GPA;
printf("Enter the Students first Name: ");
scanf("%s", &fname);
printf("\nEnter the Students last Name: ");
scanf("%s", &lname);
printf("\nEnter the Students number: ");
scanf("%s", &SN);
printf("\nEnter the Students GPA: ");
scanf("%f", &GPA);
StudentRecord* tempList;
tempList = (StudentRecord*)malloc(studentRecordSize * sizeof(StudentRecord));
int i;
studentRecordSize = studentRecordSize+1;
for(i = 0; i < studentRecordSize -1; i ++){
tempList[i].GPA = studentRecordList[i].GPA;
strncpy(tempList[i].SN, studentRecordList[i].SN,10);
strncpy(tempList[i].fname, studentRecordList[i].fname,20);
strncpy(tempList[i].lname , studentRecordList[i].lname,20);
}
printf("%f", &tempList[i].GPA );
free(studentRecordList);
studentRecordList = (StudentRecord*)malloc(studentRecordSize * sizeof(StudentRecord));
for(i=0; i < studentRecordSize; i ++){
//adds the new student at the end of the array.
if(i == studentRecordSize){
strncpy(*studentRecordList[i].fname, &fname,20);
strncpy(*studentRecordList[i].lname, &lname,20);
studentRecordList[i].GPA = GPA;
strncpy(*studentRecordList[i].SN, &SN,10);
}
strncpy(studentRecordList[i].fname, tempList[i].fname,20);
strncpy(studentRecordList[i].lname , tempList[i].lname,20);
studentRecordList[i].GPA = tempList[i].GPA;
strncpy(studentRecordList[i].SN , tempList[i].SN,10);
}
free(tempList);
}
Also if your curious here is what my save_records function looks like otherwise ignore.
void save_records(){
FILE* student_file = fopen("StudentRecordFile.dat", "w");
if(student_file == 0){
perror("cannot open StudentRecordFile.dat in load_records");
}
fprintf(student_file,"%d\n",studentRecordSize);
int i;
for(i = 0; i < studentRecordSize; i++){
fprintf(student_file,"%s\n%s\n%s\n%f\n", studentRecordList[i].SN, studentRecordList[i].fname, studentRecordList[i].lname, &studentRecordList[i].GPA);
}
}
If you need anything else let me know and ill be sure to add it, thanks.
Please try this:
in save_records() open your file binary
fopen(student_file , "wb");
then use fwrite to write the record
fwrite( &studentRecordList[i] , sizeof( studentRecordList) , 1 , student_file );
It is also easier, if you can, to write the number of records to a separate file that you open text.
This code has some problems:
for(i=0; i < studentRecordSize; i ++){
//adds the new student at the end of the array.
if(i == studentRecordSize){ // <- This can never be TRUE !!!
strncpy(*studentRecordList[i].fname, &fname,20); // Wrong
strncpy(*studentRecordList[i].lname, &lname,20);
studentRecordList[i].GPA = GPA;
strncpy(*studentRecordList[i].SN, &SN,10);
}
// Should the code below be an else ?
// If not you'll access outside tempList
strncpy(studentRecordList[i].fname, tempList[i].fname,20);
strncpy(studentRecordList[i].lname , tempList[i].lname,20);
studentRecordList[i].GPA = tempList[i].GPA;
strncpy(studentRecordList[i].SN , tempList[i].SN,10);
}
Maybe you wanted to do:
for(i=0; i < studentRecordSize; i ++){
if(i == (studentRecordSize-1)){
// Add the new record
strncpy(studentRecordList[i].fname, fname,20);
strncpy(studentRecordList[i].lname, lname,20);
studentRecordList[i].GPA = GPA;
strncpy(studentRecordList[i].SN, SN,10);
}
else
{
// Copy from the temp list
strncpy(studentRecordList[i].fname, tempList[i].fname,20);
strncpy(studentRecordList[i].lname , tempList[i].lname,20);
studentRecordList[i].GPA = tempList[i].GPA;
strncpy(studentRecordList[i].SN , tempList[i].SN,10);
}
}
A more simple version of the add function could be:
void add_record(){
char fname[20];
char lname[20];
char SN[10];
float GPA;
printf("Enter the Students first Name: ");
scanf("%s", &fname);
printf("\nEnter the Students last Name: ");
scanf("%s", &lname);
printf("\nEnter the Students number: ");
scanf("%s", &SN);
printf("\nEnter the Students GPA: ");
scanf("%f", &GPA);
StudentRecord* tempList;
tempList = (StudentRecord*)malloc(studentRecordSize * sizeof(StudentRecord));
int i;
for(i = 0; i < studentRecordSize; i ++){
tempList = studentRecordList[i];
}
free(studentRecordList);
studentRecordSize = studentRecordSize+1;
studentRecordList = (StudentRecord*)malloc(studentRecordSize * sizeof(StudentRecord));
for(i=0; i < (studentRecordSize-1); i ++){
studentRecordList[i] = tempList[i];
}
free(tempList);
// Add the new record
strncpy(studentRecordList[(studentRecordSize-1)].fname, fname,20);
strncpy(studentRecordList[(studentRecordSize-1)].lname, lname,20);
studentRecordList[(studentRecordSize-1)].GPA = GPA;
strncpy(studentRecordList[(studentRecordSize-1)].SN, SN,10);
}

Issue with array of pointers

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.

Resources