从命令行读入整数数组时遇到问题。
目的是通过空格/制表符解析输入的行,然后用 atoi() 将每个单独的数字放入适当的数组槽中。
相关代码:
main.c
#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
int main()
{
int nums[100];
int count = 0;
readInput(&nums, &count);
return 0;
}
functions.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED
void readInput(int *nums[], int *count);
#endif // FUNCTIONS_H_INCLUDED
函数.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "functions.h"
#define delims " \t\r\n"
#define MAX_LEN 128
void readInput(int *nums[], int *count)
{
char *input = malloc(MAX_LEN);
char *buffer;
gets(input);
buffer = strtok(input, delims);
nums[(*count)++] = atoi(buffer);
while ((buffer = strtok(NULL, delims)) != NULL)
nums[(*count)++] = atoi(buffer);
buffer = strtok(NULL, delims);
}
functions.c 中带有 nums[(*count)++] = atoi(buffer); 的行标记有警告“警告:赋值使指针来自整数,无需强制转换”。
在 main.c 中,readInput(&nums, &count); 行标记为 “警告:从不兼容的位置传递 'readInput' 的参数 1指针类型”。
奇怪的是,该程序在运行时有效,并且任何添加强制转换或取消引用的尝试都会导致警告被抑制,但程序在运行时崩溃。
最佳答案
当你声明你的函数时:
void readInput(int *nums[], int *count);
参数声明 int *nums[]
是一个指针数组,而不是指向数组的指针,就像使用 &nums< 那样调用它
.
但是,您不需要在此处传递指向数组的指针。数组自然会衰减为指向其第一个元素的指针。当您将数组声明为函数的参数时(如上面函数原型(prototype)中的 nums
声明),它实际上是一个指针。
声明函数参数时,int nums[]
等声明与 int *nums
相同。
所以 readInput
的声明实际上应该是
void readInput(int *nums, int *count);
如果您进行了更改(当然包括函数定义),并像这样调用它
readInput(nums, &count);
那么一切都会顺利进行。
关于C - 从命令行读入的问题 - 赋值使指针来自整数而不进行强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39301807/