TheNotoriousWMB TheNotoriousWMB - 3 months ago 16
C Question

C - issue with reading in from command line - assignment makes pointer from integer without a cast

Having an issue with reading in from the command line into an array of integers.

Intent is to parse the entered line by spaces/tabs and then atoi() each individual number into the appropriate array slot.

Relevant code:

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


functions.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);
}


The lines in functions.c with nums[(*count)++] = atoi(buffer); are flagging with the warning "warning: assignment makes pointer from integer without a cast".

And from main.c, the line readInput(&nums, &count); is flagging with "warning: passing argument 1 of 'readInput' from incompatible pointer type".

The odd thing is this program works when run and any attempts to add in casting or dereferencing has resulted in the warnings being subdued, but the program crashing when run.

Answer

When you declare your function:

void readInput(int *nums[], int *count);

the argument declaration int *nums[] is an array of pointers, not a pointer to an array which is what you call it like with &nums.

However, you don't need to pass a pointer to the array here. Arrays naturally decays to pointers to their first element. And when you declare an array as an argument to a function (like the declaration of nums in the function prototype above) it's really a pointer.

When you declare function arguments, a declaration like int nums[] is the same as int *nums.

So the declaration of readInput should really be

void readInput(int *nums, int *count);

If you do that change (including the function definition of course), and call it like

readInput(nums, &count);

then everything should work out fine.

Comments