I am trying to set up an struct with many values using command line. I give those attributes when I execute the programme in the Ubuntu 18.04ls terminal of MS store. However I'm getting a problem because I cannot get access to those attributes written on the terminal.
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TAMANIOMAXIMO 20
struct persona {
char nombre[TAMANIOMAXIMO];
int edad;
float ingresos;
}
main (int argc, char *argv[]) {
printf("%d\n", argc);
char nameProf[] = "";
stpcpy(nameProf, argv[1]);
int edadProf = atoi(argv[2]);
float ingresosProf = atof(argv[3]);
struct persona profesor = {nameProf, edadProf, ingresosProf};
struct persona alumno;
strcpy(alumno.nombre,"Juan");
alumno.edad=19;
alumno.ingresos=11.777;
printf("Los ingresos conjuntos de alumnno y profesor son %f\n",alumno.ingresos+profesor.ingresos);
exit(1);
}
The result of that execution is this one:
./a.out james 10 12
-691680792
Los ingresos conjuntos de alumnno y profesor son 11.777000
I don't know why the parameter argc (which store the number of elements of argv) has this length. I try to remove the definition of the struct 'persona' which is before main function and everything is correct. The content of argv[1], argv[2] and argv[3] is not the given as parameter in command line, argv[0] do not store "./a.out" as it should store.
For the closing braces of the definition of struct persona
, change }
to };
to end the declaration.
Change main (int argc, char *argv[])
to int main(int argc, char *argv[])
. The missing semicolon and int
resulted in a perverse declaration of main
that likely interfered with passing arguments to it, resulting in the argc
parameter being obtained incorrectly.
In char nameProf[] = "";
, the array size is taken from the initializer ""
, so it has one element, a terminating null character. Because it has only one element, the stpcpy
into it corrupts memory, causing your program to misbehave. You could change the definition to char nameProf[TAMANIOMAXIMO] = "";
. However, this array is not needed, so just delete it and the stpcpy
after it.
In struct persona profesor = {nameProf, edadProf, ingresosProf};
, you cannot initialize an array (the nombre
member) with another named array (nameProf
). (You can initialize arrays of char
with string literals, but that is not what you want here.) Just name nameProf
to {0}
to initialize the array to zeros for the moment. Then, after this line, copy the name into the array member, with strcpy(profesor.nombre, argv[1]);
. (This is why nameProf
is not needed; you can just copy the command-line argument directly into the structure member.)
Turn on warnings in your compiler and pay attention to them.