我是写stackoverflow问题的初学者,所以如果我有错误,请告诉我。
如何将 argv 数据分配给 int 数组,如下所示:
#include <cs50.h>
#include <stdio.h>
int list[];
int main(int argc, string argv[])
{
for (int i = 1; argv[i][i] != '\0'; i++)
{
list[i] = argv[i];
}
该脚本在第 10 行出错 错误信息:
selection.c:10:17: error: incompatible pointer to integer conversion assigning to 'int' from 'string' (aka 'char *') [-Werror,-Wint-conversion]
list[i] = argv[i];
我尝试了这个脚本,我希望它可以工作并且分配没有错误
#include <stdio.h>
#include <stdlib.h> // for atoi
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <num1> <num2> ...\n", argv[0]);
return 1;
}
int list[argc - 1]; // Size of the array is argc - 1
for (int i = 1; i < argc; i++) {
list[i - 1] = atoi(argv[i]); // Convert string to integer
}
// Printing the integers stored in the array for verification
for (int i = 0; i < argc - 1; i++) {
printf("list[%d] = %d\n", i, list[i]);
}
return 0;
}