What is the correct syntax for specifying an array of characters as a function parameter?

advertisements

What is the correct syntax for specifying an array of characters as one of the parameters of a function?

I don't know if I am stressed and unable to find the error or because i have been away from C for a while. I just cannot spot the error. Please help!

#include <stdio.h>
#include <string.h>
void reverseWord(int len, char[] str, int index)
{
    int start, end;
    char temp;
    start = index - len;
    end = index - 1;
    while (start <= end)
    {
        temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end --;
    }
}

void main()
{
    int i,j=0, len;
    int tmp = 0;
    char str[]="i am a loser";
    char word[]= " ";
    len = strlen(str);
    for(i=0;i<len;i++)
    {
        if(str[i] == ' ')
        {
            tmp = strlen(word);
            if(tmp != 0)
            {
                 reverseWord(tmp , str ,i);
                 j = 0; <<ERROR PRONE LINE>>
            }
        }
       else
           word[j++]=str[i];
    }

    printf ("final string = %s",str);
}

I keep getting this error

error: expected ‘;’, ‘,’ or ‘)’ before ‘str’ on line marked above


The issue is in the definition of str in reverseWord function. Instead of char[] str, if you modify the same to char* str, your compilation will be successful.

If you wish to use the [] concept, then one potential solution could be to define a new data type as

typedef char myArrStr[100];

which defines myArrStr to be an 100 element character array.

In the function definition of reverseWord, you could modify the definition to

void reverseWord(int len, myArrStr str, int index)

The definition of str could be modified as

myArrStr str = "i am a winner"; // Changed your message :-)

With these updates, your code should just work fine.