How to acces pointer in a structure - c

This is my code :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct pers
{
int age;
char *name;
float height;
}Person;
void read(Person p[], int *nr) // an array of persons, and nr is the number of persons
{
scanf("%d", nr);
int i;
for(i = 0; i < *nr; i++)
{
scanf("%d", &p[i].age);
p[i].name = calloc(100, sizeof(char));
scanf("%s", p[i].name);
scanf("%f", &p[i].height);
}
}
int main()
{
int nr;
Person p[100];
int i;
read(p, &nr);
for(i = 0; i < nr; i++)
{
printf("%d\n", p[i].age);
printf("%s\n", p[i].name);
printf("%f\n", p[i].height);
}
return 0;
}
I don't know why this not stocate well the data . How can i do with pointers or anything else, to have acces to age and height and also to the *name
If i try only with age and height the code works, but when i add the name, it stucks.
this is my input
3 // numbers of persons
23 // age
John Smith //firstname + lastname //1person
182.5 //height
18
Mat Plow //2person
152.6
56
Alex Grim //3person
172
Any ideas?
i think i might use gets and with some pointer, but i don't know how :D
Thank you !

Because there is nothing wrong with your code, there must be something wrong with your scanf input specification. Check/read the input format specifier documentation. For '%s' it says: "String, up to first white-space character (space, tab or newline)" so if name is "Firstname Lastname" it will only read "Firstname".
Also, you can add debug statements to see what has been read so-far, or you can use a debugger to step through the code to see what happens. A scanf-guru can tell you right away what's wrong; all others must read the documentation.

scanf(" %[^\n]s", p[i].name);
This is what works for me !

Change your scanf call to this:
scanf("%s\n", p[i].name);
Please note the \n added.

Related

Reading strings to an array

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]);

Why does my program exit after taking an input?

Consider:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n;
char name[100];
int number;
printf("Enter the value of n\n");
scanf("%d",&n);
printf("Enter %d values\n", n);
for(int i=0; i<n; i++)
{
scanf("%[^\n]s", &name);
}
}
Whenever I am entering the value of n, it just prints (Enter n values) and exits the program. The for loop never runs. It ran successfully for the first time, but after that it just exits the program.
There were some answers that said it will not print anything. I don’t want it to print just to take input n times. It is not doing that.
My aim is to take n as input and then take strings of names (like harry, robin, etc.) n number of times as input.
Your code is a little incomplete. And there are a few errors here: scanf ("%[^\n]s", &name)
Do this and everything will be fine:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main(void)
{
int n;
char name[100];
int number;
printf("Enter the value of n\n");
scanf(" %d", &n);
printf("Enter %d values\n", n);
for(int i=0; i<n; i++)
{
scanf(" %99[^\n]", name);
printf("%s\n", name);
}
return 0;
}
scanf is particularly unsuited for user input.
You probably want this:
int main() {
int n;
char name[100];
int number;
printf("Enter the value of n\n");
scanf("%d", &n);
printf("Enter %d values\n", n);
for (int i = 0; i < n; i++)
{
// the space at the beginning of "%[^\n]"
// gets rid of the \n which stays in the input buffer
scanf(" %[^\n]", name); // also there sis no 's' at the end of the "%[^\n]" specifier
printf("name = %s\n", name); // for testing purposes
}
}
But this doesn't actually make much sense because the program is asking for n names, but at each run of the for loop the previous name will be overwritten with the new name.
Also be aware that scanf("%[^\n]", name); is problematic because if the user types more than 99 characters you'll get a buffer overflow.

I can't type all the information in an array of structs

When I try to compile this small program everything is correct but when I run it I find some problems. For example, I can't type the "c" variable in the second element of the table and so on.
#include <stdio.h>
struct point{
char c;
int x,y;
};
int main(void)
{
int size = 4;
struct point tp[size];
for(int i = 0; i < size; i++ )
{
printf("entrer le nom du point no %d: ", i+1);
tp[i].c = fgetc(stdin);
printf("x = ");
scanf("%d", &tp[i].x);
printf("y = ");
scanf("%d", &tp[i].y);
}
}
There are a lots of similar questions here, for example: C scanf() and fgets() problem, fgets doesn't work after scanf.
You could use fgets() for user input and parse string with sscanf() for example.
Or you can use fgetc(stdin); after each scanf() to get rid of '\n' symbol.

Malloc for structures

I am not getting the correct output here,
The code takes the no of inputs and option as an input, then takes the name of student year and gender and based on option provided gives the output. The output can be the name appearing first in the dictionary or the smaller value of the year amongst the inputs.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct student_record
{
int passing_year;
char gender;
char name[20];
};
typedef struct student_record student;
student* find_specific(student* find, int option_num, int number)
{
int i;
student* temp = find;
int opt = option_num;
int num = number;
if(opt==1)
{
for(i=0; i<num; i++)
{
if( strcmp(temp->name, find[i].name) >0)
temp = find+i;
}
}
else
{
for(i=0; i<num; i++)
{
if (temp->passing_year > find[i].passing_year)
temp = find+i;
}
}
return temp;
}
int main() {
student* example;
student* final;
int i;
int option_num, number_of_students;
printf("Enter 2the number of students, option number");
scanf("%d" "%d", &number_of_students, &option_num);
example = (student* )malloc(number_of_students * sizeof(student));
printf("Enter the name, passing year and gender");
for(i=0; i< number_of_students; i++)
{
scanf("%s" "%d" "%c", example[i].name, &example[i].passing_year, &example[i].gender);
}
final = find_specific(example, option_num, number_of_students);
printf("%s" "%d" "%c", final->name, final->passing_year, final->gender );
return 0;
}
i am getting a segmentation fault. I can't figure out exactly where am I screwing up.
Your scanf() and printf() format strings are probably wrong.
scanf("%s" "%d" "%c", example[i].name, &example[i].passing_year, &example[i].gender);
should probably be
scanf("%s %d %c", example[i].name, &example[i].passing_year, &example[i].gender);
(without the extra quotes). The compiler will concatenate adjacent
string literals, so instead of a compiler error, it interpreted your format string as equivalent to "%s%d%c" (without whitespace in between).
That probably doesn't match the layout of your input, so some of the values were probably left uninitialized in a way that caused problems later.
You should always check the return value of scanf and similar library functions,
to ensure that you got the input format you told the compiler to expect.

while loop asks user input one time only

#include <stdio.h>
#include <stdlib.h>
struct the_struct
{
char FirstName[20];
char LastName[32];
int Score[20];
};
int main ()
{
int i,n;
struct the_struct *ptr[100];
printf("how many students?\n");
scanf("%d",&n);
while (i<=n);
{
i==0;
ptr[i] = malloc(sizeof(struct the_struct));
printf("Enter First Name \n");
scanf("%s",ptr[i]->FirstName);
printf("Enter Last Name \n");
scanf("%s",ptr[i]->LastName);
printf("Enter Score? \n");
scanf("%s",ptr[i]->Score);
printf("%s %s %s\n",ptr[i]->FirstName,ptr[i]->LastName,ptr[i]->Score);
i++;
}
}
hey guys, so when i enter the first input, it goes only once without going on for the number the user inputs, i tried the for loop but same result.
still learning C so my apology if i misunderstood something.
Thanks in advance.
Your while loop is problematic. You could rewrite it as:
for (i = 0; i < n; ++i)
{
ptr[i] = malloc(sizeof(struct the_struct));
printf("Enter First Name \n");
scanf("%s",ptr[i]->FirstName);
printf("Enter Last Name \n");
scanf("%s",ptr[i]->LastName);
printf("Enter Score? \n");
scanf("%s",ptr[i]->Score);
printf("%s %s %s\n",ptr[i]->FirstName,ptr[i]->LastName,ptr[i]->Score);
}
And since you use %s to read and print Score, you should declare it as char Score[20]; instead of int.
The problem is that i is uninitialized. Therefore, the loop while (i <= n) has undefined behavior, and can end at any time.
Add int i = 0 initializer to fix this problem.
Notes:
i == 0 expression at the beginning of the loop has no effect
Since i starts at zero, your while loop should be while (i < n), not <=.
You should check the results of scanf to see if the user entered something meaningful
You should specify the size of the array into which you read a string, e.g. scanf("%31s",ptr[i]->LastName); This prevents buffer overruns.

Resources