Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing pointer to string, incompatible pointer type

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
}
like image 322
Skyler_Babudro Avatar asked Oct 21 '22 01:10

Skyler_Babudro


2 Answers

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.

like image 143
haccks Avatar answered Nov 03 '22 03:11

haccks


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
like image 41
Abhishek Choubey Avatar answered Nov 03 '22 03:11

Abhishek Choubey