0
votes

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.

3
What is the program supposed to do? - Barmar
char *numbers = malloc(count * sizeof(char) + 1); int j = 0; for(i = 1 ; i <= count; i++){ printf("%s ", argv[i]); numbers[j++] = *argv[i]; } numbers[j] = 0; - BLUEPIXY
I wanted to print the values passed to argv one at a time. Then print at one go the items together. - Tamal Chakraborty
You mean you are trying to concatenate strings? - M.M

3 Answers

0
votes

You have to dereference argv twice to get the char value numbers[i] = *(*(argv + i));

1
votes

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.

0
votes

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);