简体   繁体   中英

How to assign to char from const char *

I have the following C code

int main (int argc, const char *argv[]){

int counter = 1;
char input[1000000];

while(argv[counter] != NULL){
input[counter] = argv[counter]
}

return 0;
}

This gives the warning incompatible pointer to integer conversion assigning to 'char' from 'const char *' [-Wint-conversion]

I can loop through and print out the values of argv[counter] so im confused why i can't set a variable equal to them.

argv is an array of const string while input is an array of character. So your first step is to make input array of string by doing this char *input[1000000] and lastly you have to cast each const string of argv before assigning it to input by doing this input[counter] = (char *)argv[counter] .

Edit Suggested By @David Ranieri

You can remove const from argv to avoid the casting.

ALSO

As @NoDakker said in the comment section. You have to increment counter to avoid infinite loop.

Solution

#include <stdlib.h>

int main (int argc, const char *argv[]){

int counter = 1;
char *input[1000000];

while(argv[counter] != NULL){
input[counter] = (char *)argv[counter];
counter++;
}

return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM