Reputation: 31
My code is:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]){
int i = 0;
int count = argc - 1;
char *numbers = malloc(count * sizeof(char));
for(i = 1 ; i <= argc ; i++){
printf("%s ", argv[i]);
numbers[i] = argv[i];
}
printf ("%s \n", numbers);
return 0;
}
The error that came is:
tamal@baba-desktop:~/Desktop/c$ cc experiment.c -o experiment
experiment.c: In function ‘main’:
experiment.c:10:16: warning: assignment makes integer from pointer without a cast [enabled by default]
I tried numbers[i] = &(argv[i]);
at line 10. Still the same result.
Upvotes: 0
Views: 5780
Reputation: 122
This should be done as if there are more than 2 arguments:
int count = argc - 1;
char **numbers = (char **)malloc(count * sizeof(char*));
for(i = 0 ; i < argc ; i++){
printf("%s ", argv[i + 1]);
// Stores all arguments except "experiment"(i.e. exe file).
numbers[i] = argv[i + 1];
}
for(i = 0; i <= count; i++){
printf("%s\n", numbers[i]);
}
And if there is only two arguments then it should be done simply as:
char *number = (char *)malloc(1*sizeof(char));
// Store argument other than provided .exe file i.e. "experiment"
number = argv[1];
printf("%s\n", number);
Upvotes: 0
Reputation: 78
You have to dereference argv twice to get the char value numbers[i] = *(*(argv + i));
Upvotes: 0
Reputation: 134286
In your code, numbers[i]
is of type char
, whereas, argv[i]
is of type char *
and both are not the same. That's why the warning is there.
In the second case, numbers[i] = &(argv[i]);
is also wrong, as &(argv[i]);
is also not a char
.
The bottom line is, you have a char
pointer numbers
and when you use indexing operator on it, you get the inidiviual elements as char
, i.e., all the numbers[i]
are of type char
. You need to assign another char
value to it.
Upvotes: 1