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

问题描述 投票:-4回答:1

当我尝试将atoi与int和malloc一起使用时,出现一堆错误,并且给键赋了错误的值,我在做什么错?

#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);
}
c pointers malloc atoi
1个回答
0
投票

您可能想要这个:

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

我还建议您阅读初学者的C课本中有关字符串的章节。

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


0
投票

您可能想要这个:

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

我还建议您阅读初学者的C课本中有关字符串的章节。

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

© www.soinside.com 2019 - 2024. All rights reserved.