如何将atoi与int和malloc一起使用?

如何将atoi与int和malloc一起使用?,c,pointers,malloc,atoi,C,Pointers,Malloc,Atoi,当我尝试将atoi与int和malloc一起使用时,我会遇到一系列错误,并且key被赋予了错误的值,我做错了什么 #include <stdio.h> #include <stdlib.h> #include <string.h> struct arguments { int key; }; void argument_handler(int argc, char **argv, struct arguments *settings); int

当我尝试将atoi与int和malloc一起使用时,我会遇到一系列错误,并且key被赋予了错误的值,我做错了什么

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct arguments {
    int key;
};

void argument_handler(int argc, char **argv, struct arguments *settings);

int main(int argc, char **argv) {
    argv[1] = 101; //makes testing faster
    struct arguments *settings = (struct arguments*)malloc(sizeof(struct arguments));
    argument_handler(argc, argv, settings);
    free(settings);
    return 0;
}

void argument_handler(int argc, char **argv, struct arguments *settings) {
    int *key = malloc(sizeof(argv[1]));
    *key = argv[1];
    settings->key = atoi(key);
    printf("%d\n", settings->key);
    free(key);
}

你可能想要这个:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct arguments {
  int key;
};

void argument_handler(int argc, char** argv, struct arguments* settings);

int main(int argc, char** argv) {
  argv[1] = "101";  // 101 is a string, therefore you need ""
  struct arguments* settings = (struct arguments*)malloc(sizeof(struct arguments));
  argument_handler(argc, argv, settings);
  free(settings);
  return 0;
}

void argument_handler(int argc, char** argv, struct arguments* settings) {
  char* key = malloc(strlen(argv[1]) + 1);  // you want the length of the string here,
                                            // and you want char* here, not int*

  strcpy(key, argv[1]);                    // string needs to be copied
  settings->key = atoi(key);
  printf("%d\n", settings->key);
  free(key);
}

免责声明:我只是纠正了明显错误的地方,仍然需要进行检查,例如,如果argc小于2等。

最明显的是,您正在做的奇怪/错误的事情是,atoi将一个char*作为唯一的参数,并且您正在传递一个int*我得到一系列错误-什么错误?argv[1]=101;毫无意义。当我用-Wall-Wextra编译这篇文章时,我得到了四条警告,这对于这么短的一段代码来说太多了。激活警告。这四条警告都指出了代码中的缺陷,但还有更多的东西
void argument_handler(int argc, char** argv, struct arguments* settings) {
  settings->key = atoi(argv[1]);
  printf("%d\n", settings->key);
}