I wrote the following code which is supposed to read an input, n = number of people, then create an array of structs the size of n, then read the info of each person and finally print all the info in order.
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
struct person {
char name[51];
int age;
};
struct person list[n];
int i;
for(i = 0; i < n; i++) {
scanf("%s", list[n].name);
scanf("%d", &list[n].age);
}
for(i = 0; i < n; i++) {
printf("Name: %s - Age: %d\n", list[i].name, list[i].age);
}
return 0;
}
So I compiled it using GCC on Ubuntu, executed and provided the following inputs:
1
Lucia
60
But instead of getting Name: Lucia - Age: 60 on the terminal, I'm getting Name: �rI�� - Age: 32766 which I believe is random trash in the computer's memory. I'm using the same treatment of arrays of structs I see in some web pages and in my college's material, so why doesn't it store the data properly?
Since you used i in your for loop, you should end up calling it as well in your scanfs not n. Change it to:
for(int i = 0; i < n; i++) {
scanf("%s", list[i].name);
scanf("%d", &list[i].age);
}
and this should do the trick!
Related
I wrote a simple program to take names and numbers from the user and store it in an array, then compare between each cell until it reach the maximum grade then it displays it. The problem is that when it run it shows a message (segmentation fault (Core dump)). I really don't know what my mistake is.
#include <stdio.h>
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", & n);
char name[n];
float score[n];
for (int i = 0; i < n; i++) {
printf("\nEnter the name of Student: ");
scanf("%s", & name[i]);
printf("\nEnter the score: ");
scanf("%f", & score[i]);
}
float max;
int index;
max = score[0];
index = 0;
for (int i = 1; i < n; i++) {
if (max < score[i]) {
max = score[i];
index = i;
}
}
printf("\nHighest mark scored is %f by student %s", name[index], score[index]);
}
1- you use user input to define the size of an array (wrong)
-- array in c has static size so you must define it's size before the code reach the compiling stage(use dynamic memory allocation instead)
2- scanf("%s", & name[I]); you want to save array of char and save the address at the name variable but name it self not a pointer to save address it's just of char type (wrong)
-- you need pointer to save the address of every name so it's array of pointer and a pointer to allocate the address of the array to it so it's a pointer to poiner and define max size of word if you define size the user input exceed it will produce an error
3- finally you exchanged the %f,%s in printf
#include <stdlib.h>
#include <stdio.h>
#define SIZE_OF_WORD 10
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", & n);
char **name=(char**)malloc((sizeof(char*)*n));
for (int i = 0; i < n; i++) {
name[i]=(char*)malloc((sizeof(char)*SIZE_OF_WORD));
}
float *score=(float*)malloc((sizeof(float)*n));
for (int i = 0; i < n; i++) {
printf("\nEnter the name of Student: ");
scanf("%s", name[i]);
printf("\nEnter the score: ");
scanf("%f", & score[i]);
}
float max;
int index;
max = score[0];
index = 0;
for (int i = 1; i < n; i++) {
if (max < score[i]) {
max = score[i];
index = i;
}
}
printf("\nHighest mark scored is %s by student %.0f\n", name[index],score[index]);
}
I want to make a simple variable for number of the round for a loop, so I tried my code
int size,counter,marks[size];
scanf("enter %d/n",&size);
for(counter=0;counter<size;counter++)
{
scanf("%d",&marks[counter]);
}
and compiled with no error but in run, it just shows "process returned -1073741571 <0*c00000FD>.
so I tried gets function and it shows "too many arguments to function 'gets' ".
int size;
int counter;
int marks[size];
scanf("enter %d/n",&size);
for(counter=0;counter<size;counter++)
{
gets("%d",&marks[counter]);
}
I'm using code::blocks 17.12 and the gnu compiler.
size can have any value when the array marks is allocated because it is not initialized. The array might be smaller than the entered size and so marks are stored in non-allocated memory, giving you the error.
This is a possible solution, but it doesn't compile with strict ISO C90. Presumably your CodeBlocks uses GCC that accepts variable length arrays and mixed declarations and code.
#include <stdio.h>
int main(void) {
int size;
printf("enter size: ");
scanf("%d",&size);
int marks[size];
int counter;
for (counter = 0; counter < size; counter++) {
scanf("%d", &marks[counter]);
}
for (counter = 0; counter < size; counter++) {
printf("%d: %d\n", counter, marks[counter]);
}
return 0;
}
BTW, please don't say "build error" if you have a runtime error. ;-)
Please don't use gets. It's dangerous.
As for your error in the scanf example, the first problem is the line
int size,counter,marks[size];
which declares marks with the uninitialized size value. Try initializing size first, then declaring the marks array.
Your second problem is scanf formatting string. Use scanf to read formatted input, not output a prompt. Use puts or printf for that.
Here's a full example:
#include <stdio.h>
int main(void) {
int size;
printf("Enter a size value: ");
scanf("%d", &size);
int marks[size];
for (int i = 0; i < size; i++) {
printf("Enter element %d: ", i);
scanf("%d", &marks[i]);
}
printf("You entered: ");
for (int i = 0; i < size; i++) {
printf("%d ", marks[i]);
}
puts("");
return 0;
}
Here's a sample run:
Enter a size value: 4
Enter element 0: 88
Enter element 1: 77
Enter element 2: 66
Enter element 3: 55
You entered: 88 77 66 55
If you're writing ANSI C-compatible code you can use dynamic memory with malloc:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i, size, *marks;
printf("Enter a size value: ");
scanf("%d", &size);
if (size < 1) {
fprintf(stderr, "Invalid size specified\n");
exit(1);
}
marks = malloc(size * sizeof(int));
if (!marks) {
fprintf(stderr, "malloc failed\n");
exit(1);
}
for (i = 0; i < size; i++) {
printf("Enter element %d: ", i);
scanf("%d", &marks[i]);
}
printf("You entered: ");
for (i = 0; i < size; i++) {
printf("%d ", marks[i]);
}
free(marks);
puts("");
return 0;
}
size must have a defined value, for example:
#include <stdio.h>
int main()
{
int size;
size = 5; // size must be constant
int counter, marks[size];
for (counter = 0; counter < size; counter++)
{
scanf("%d", &marks[counter]);
}
//Printing it returns correct values:
for (counter = 0; counter < size; counter++)
{
printf("%d\n", marks[counter]);
}
}
You can instead input it's value from the user if you want.
However, if for some reason, size is to be defined after the array is declared, use pointers:
#include <stdio.h>
#include "stdlib.h"
int main()
{
int size;
int counter, *marks;
size = 5; //declared after the array
marks = (int *)malloc(size * sizeof(int));
for (counter = 0; counter < size; counter++)
{
scanf("%d", &marks[counter]);
}
//Printing it returns correct values:
for (counter = 0; counter < size; counter++)
{
printf("%d\n", marks[counter]);
}
//Don't forget to free the array in the end
free(marks);
}
Please tell me what's wrong with this code.
Program to input number of students, their names and then print their names.
#include <stdio.h>
int main() {
int n, i;
scanf("%d", &n); // number of students
char* names[n]; // array of pointers.
for(i = 0; i < n; i++) {
scanf("%100[^\n]", names[i]); //student names
}
for(i = 0; i < n; i++){
printf("%s", names[i]); // printing students names
}
}
It does not show any error on compiling but it does not work.
So I want to sort the list so that i can give them their position according to their grades but it's not working.
It is Showing error like : incompatible types when assigning to type char from type struct info.
p.s : I am trying to do this sorting using Structures.
#include <stdio.h>
#define SIZE 3
struct info {
char name[20];
int number;
double grade;
};
int main(void) {
struct info list[SIZE];
int i, j;
char temp;
int avg;
for (i = 0; i < SIZE; i++) {
printf("Enter your name : ");
scanf("%s", list[i].name);
printf("Enter your number : ");
scanf("%d", & list[i].number);
printf("Enter your grade : ");
scanf("%lf", & list[i].grade);
}
for (i = 0; i < SIZE; i++) {
printf("Name : %s Student Number : %d Grade : %f", list[i].name,
list[i].number, list[i].grade);
printf("\n");
}
for (i = 0; i < SIZE; i++) {
for (j = i + 1; j < SIZE; j++) {
if (list[j].grade > list[i].grade) {
temp = list[j];
list[j] = list[i];
list[i] = temp;
}
}
}
for (i = 0; i < SIZE; i++) {
printf("%d st Position : Name : %s Student Number : %d Grade : %f ",i,
list[i].name, list[i].number, list[i].grade);
printf("\n");
}
avg = 0;
for (i = 0; i < SIZE; i++)
avg += list[i].grade;
avg = avg / 3;
printf("Average is %d", avg);
getch();
return 0;
}
errors are in the following code:
for(i=0;i<SIZE;i++) {
for(j=i+1;j<SIZE;j++) {
if(list[j].grade>list[i].grade) {
temp=list[j];
list[j]=list[i];
list[i]=temp;
}
}
}
You assign a type char with name temp and try to assign a struct to it. Instead create a struct temp and then sort your array of structs.
#include <stdio.h>
#define SIZE 3
struct info { // use typedef struct info instead
char name[20];
int number;
double grade;
};
int main(void) {
struct info list[SIZE]; // allows you to write info list[size]
int i, j; // do not initialize loop variables outside of their loops unless you need to(makes it easier to read the loop statements/spot mistakes)
char temp; // you need to use a type info, not char e.g. info temp
I can not compile it myself at the moment, so please let us know in the comments if you have any further questions.
I am trying to print the records after adding on to the original amount of records, and I am successful in doing so within the addRecords function, but outside of the function I have an error, but I am having understanding how. I'm passing the Names array through pointer and the classSize variable is global. So I don't see why it works in the addRecords function and not in the main funtion. All help is appreciated, thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#define STRINGSIZE 21
int classSize;
void addRecords( char **Names);
int main() {
char **Names;
int i;
//User will be able to choose how many records he woudld like to input.
printf("Please indicate number of records you want to enter:\n");
scanf("%d", &classSize);
Names = malloc(classSize*sizeof(char*));
for (i = 0; i < classSize; i++) {
Names[i] = malloc(STRINGSIZE * sizeof(char));
}
printf("Please input records of students (enter a new line after each record), with following format: first name....\n");
for (i = 0; i < classSize; i++) {
scanf("%s", *(Names + i));
}
for (i = 0; i < classSize; i++) {
printf("%s ", *(Names+i));
printf("\n\n");
}
addRecords(Names);
printf("SECOND PRINT\n\n");
for (i = 0; i < classSize; i++) {
printf("%s \n", *(Names+i));
}
}
void addRecords(char **Names) {
int addition, i, temp;
temp = classSize;
printf("How many records would you like to add?\n");
scanf("%d", &addition);
classSize += addition;
Names = realloc(Names, (classSize) * sizeof(char*));
for (i = temp; i < (classSize); i++) {
Names[i] = malloc(STRINGSIZE * sizeof(char));
}
printf("Please input records of students (enter a new line after each record), with followingformat: first name....\n");
for (i=temp; i<classSize; i++) {
scanf("%s", *(Names +i));
}
printf("\n\n");
printf("FIRST PRINT\n\n");
for (i = 0; i < classSize; i++) {
printf("%s \n", *(Names+i));
}
printf("\n\n");
}
C uses pass-by-value. The Names inside addRecords is a different variable to Names inside main. A copy is created when you call the function.
To fix this you either need to pass Names by reference, or make it a global variable, or return the updated copy via function return value.
In your actual code, attempting to use Names in main() after it had been passed to realloc in the function, causes undefined behaviour (realloc makes its argument indeterminate).