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

标签 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 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);
}

但这很尴尬,实际上argument_handler可以这样重写:

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

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

关于c - 如何将 atoi 与 int 和 malloc 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59304685/

相关文章:

c - 从c中的函数返回一个float类型

C 字符串有随机尾随字符、空终止问题?

c++ - 如何在 C++ 中从头开始反序列化文件(没有库)

c++ - 回到指针位置

C程序给出奇怪的输出

c - UTF8控制台输出: MultiByteToWideChar vs mbsrtowcs

c - 无法使用 <sys/times.h> ubuntu 进行编译

c - libarchive 提取文件时读取的字符过多

c - 如何将内存中的结果放入文件 *.txt

C- 如何释放以下 malloced 内存