My program takes name and age from command line arguments through name and stores each name and age as elements of a structure. My problem is strcpy crashing my program when I run it. Here is my code, I would appreciate any help that I can get.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct {
char name[80];
int age;
} person;
int main(int argc, char *argv[]){
if (argc == 1 || argc % 2 == 0) {
printf("Invalid arguments.\n Usage: %s name1 age1 name2 age2 ...", argv[0]);
return 0;
}
person people[argc/2];
int i;
for (i = 0; i < argc; i++)
strcpy(people[i].name, argv[i+1]);
The problem is with this loop here:
You have two out-of-range array references:
You are looping from 0..argc-1, so you are referencing argv from 1..argc - ie. out of range.
Also, you are creating an array of length argc/2 but you are referencing elements 0...argc - ie. another array overflow.
The loop should be something like: