Reputation: 165
I essentially want to read values from the command line as typed in by the user and place them into an array. My attempt at this so far is as follows
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define w 1.0
int main(int argc, char argv[])
{
int tmp;
double *x, *v, *m, *k, *R;
x = malloc((argc-1)*sizeof(double));
printf("%lf\n", argc);
for(tmp=0; tmp<argc-1; tmp++)
{
x[tmp] = argv[tmp+1];
printf("%lf\n", x[tmp]);
}
}
The print of the value of argc is equal to 0 yet the for loop will repeat three times which doesn't make sense and the values it gives are just completely wrong. Sorry i'm a bit of an amateur at this. Thanks in advance!
Upvotes: 0
Views: 122
Reputation: 86
int main(int argc, char* argv[])
{
int i;
//calloc = malloc for N elemnts of given size
double* myArray = (double*)calloc(argc, sizeof(double));
//Check out arg 0!
for (i = 0; i<argc; i++)
{
printf("arg [%d] = %s\n",i,argv[i]);
}
for (i = 1; i<argc; i++)
{
sscanf(argv[i], "%lf", &myArray[i]);
printf("myArray[%d] = %f\n",i, myArray[i]);
}
//avoid memory leak
free(myArray);
}
I see that my answer came a bit to late, anyways I just wanted to point out the arg[0] is not input.
Upvotes: 0
Reputation: 30136
printf("%lf\n", argc)
will cause a memory access violation, because:
argc
is an integer type (4 bytes).
printf("%lf...
attempts to read 8 bytes.
You must change it to printf("%d\n", argc)
.
Upvotes: 0
Reputation: 47533
There are many problems with your code, some already mentioned by others such as argv
that needs to have a type of char *[]
.
First of all, if argc
is 1, then your malloc
will fail because allocating memory of size 0 doesn't make sense.
Second, printf("%lf\n", argc);
is incorrect. argc
is int
and you need to use %d
to print it. The reason you see 0, which is wrong, is this.
Third, x[tmp] = argv[tmp+1];
is incorrect too. argv[tmp+1]
is a char *
, which means it's a string. While x[tmp]
is a double
. You can't just assign a string to a double. What you need to do is to convert the string to a double, for example:
sscanf(argv[tmp+1], "%lf", &x[tmp]);
or
x[tmp] = strtod(argv[tmp+1]);
Hint: always compile your code with common warnings. With gcc, that would be -Wall
command line argument. The compiler can tell you about many of these mistakes.
Upvotes: 2
Reputation: 60007
For a start the signature of main should be
int main(int argc, char *argv[])
Then you are passed strings. You need to convert them to doubles sscanf
will do this - see http://linux.die.net/man/3/sscanf
Upvotes: 1