5
votes

So I'm sure this question is answered many times already but I am having trouble seeing how to fix my situation. I took a snippet of my program that contains my warning-generating code:

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

inputData(int size, char *storage[size])
{
    int iterator = -1;

    do {
        iterator++;
        *storage[iterator] = getchar();
    } while (*storage[iterator] != '\n' && iterator < size);
}

main()
{
    char name[30];

    inputData(30, name);
}

The warning message:

$ gcc text.c text.c: In function ‘main’: text.c:18:5: warning: passing argument 2 of ‘inputData’ from incompatible pointer type [enabled by default] inputData(30, name); ^ text.c:4:1: note: expected ‘char **’ but argument is of type ‘char *’ inputData(int size, char *storage[size])

EDIT:

Ok, so I managed to play around with some syntax and fixed my problem. I still wouldn;t mind hearing from somebody more knowledgeable than I why precisely this was needed. Here is what I changed:

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

inputData(int size, char *storage) // changed to point to the string itself 
{
    int iterator = -1;

    do {
        iterator++;
        storage[iterator] = getchar(); // changed from pointer to string
    } while (storage[iterator] != '\n'); // same as above
}

main()
{
    char name[30];

    inputData(30, name);

    printf("%s", name); // added for verification
}
2
Inside inputData(), code should have 3 reasons to stop: 1) getchar() returned '\n' 2) getchar() returned EOF 3) No more room.chux - Reinstate Monica

2 Answers

2
votes

Array name converted to pointer to its first element when passed to a function. name will be converted to &name[0] (pointer to char type) which is the address of first element of array name. Therefore, second parameter of your function must be of pointer to char type.

char *storage[size] is equivalent to char **storage when declared as function parameter. Therefore, change char *storage[size] to char *storage.

1
votes

When you pass an array to a function, you can do it in 2 ways :
Consider the following program :-

int  main()
{
   int array[10];
   function_call(array); // an array is always passed by reference, i.e. a pointer   
   //code                // to base address of the array is passed.
   return 0;
} 

Method 1:

void function_call(int array[])
{
  //code
}

Method 2:

void function_call(int *array)
{
  //code
}

The only difference in the two methods is the syntax, otherwise both are the same.
It is worth mentioning that in C language the arrays are not passed by value but by
reference.
You might find the following link useful : -

http://stackoverflow.com/questions/4774456/pass-an-array-to-a-function-by-value