Reputation: 705
Hello i want to copy the input of a user into an array of char which is defined in a struct. Sincerly i have no idea how to do this.
#include <stdio.h>
#include <stdlib.h>
int main ()
{
struct employee
{
char firstname[11];
char lastname[11];
char number[11];
int salary;
}
int i;
int nemps;
const int maxemps = 5;
struct employee* emps[maxemps];
printf("How many employees do you want to store?(max:5): ");
scanf("%d", nemps);
for (i = 0; i < nemps; i++)
{
printf("Employee 1./nLast name:");
scanf("....")// Read the string and copy it into char lastname[]
}
}
Upvotes: 0
Views: 5300
Reputation: 140237
First off struct employee* emps[maxemps];
creates an array of pointers to struct employee with array size maxemps. You haven't actually set aside any space in memory for the actual structs, just the pointers that will point to them. To dynamically allocate space on the heap for your structs so you can use them in a meaningful way, you'll need to loop over a call to malloc()
like so:
for (i = 0; i < maxemps; i++) {
emps[i] = malloc(sizeof(struct employee));
}
You'll also want a similar loop at the end of your program which will free()
each pointer.
Next, when you are getting input from a user you really want to be using fgets()
over scanf()
because fgets()
allows you to specify the number of characters to read in so you can prevent overflows on your destination buffer.
If you want to work with a single struct employee
without the use of pointers this is accomplished by declaring one or more struct employee
on the stack and then using the .
member access operator as follows:
struct employee emp;
fgets(emp.lastname, sizeof(emp.lastname), stdin);
I found a number of errors in your code. Please see this link for a working sample with comments.
Upvotes: 3
Reputation: 9330
You only need:
scanf("%10s", (emps[i])->last_name);
Here "%10s"
denotes a string with a maximum length of 10, and it will load the string to last_name.
In C the string is represented as a char array, with '\0'
as the end.
Using scanf
here is vulnerable to buffer attacks if the user-input is longer than 10: http://en.wikipedia.org/wiki/Scanf#Security, so you need to assign a maximum length to the format.
Upvotes: 2