0

So, I'm trying to do the following with some C code:

int eval_setence(char *words){
...
}

void main(){
char *words[8];
eval_setence(words);
}

But I'm don't know why the code is not compiling, I assume the function is getting a double pointer to words[8]. Could someone explain what's going on?

I'm trying to do operations with the words[8] inside the function, i.e:

if(words[i] == 'Wow')
...
12
  • 1
    Please post the compiler output. Commented Apr 28, 2015 at 20:20
  • 1
    Use char ** as your function argument. Also note that you can't compare strings with ==, and strings must be double-quoted, not single-quoted.
    – user12205
    Commented Apr 28, 2015 at 20:21
  • 1
    @Zetsuno so just do what compiler says. Commented Apr 28, 2015 at 20:22
  • 1
    You should be able to use strlen(words[0]), strlen(words[1]) etc.
    – user12205
    Commented Apr 28, 2015 at 20:24
  • 2
    @Zetsuno: It's non-standard. The C standard specifies either int main(void) or int main(int argc, char *argv[]), or equivalent. Other implementation-defined forms are permitted, but there is really no good reason to use void main(). The very same standard that introduced the void keyword also specified int as the return type for main. See questions 11.12a and following in the comp.lang.c FAQ. Commented Apr 28, 2015 at 20:40

2 Answers 2

3
int eval_setence(char *words){
...
}

void main(){
char words[8];
eval_setence(words);
}

Your words variable was a pointer to a char pointer, you should define an array this way:

type var[len];

Not:

type *var[len];

Or, if you need a two dimensional array (which I suppose you do), you should define it like this:

type var[len1][len2];

This should be trivial however.

1
  • You're right, it was trivial, I was just overthinking it way too much, thanks tho!
    – Zetsuno
    Commented Apr 28, 2015 at 20:29
1

The problem is that

char *words[8]; 

declares words as an array of pointers to chars. When this is passed to a function it is converted to a pointer to a pointer to chars. If you want an array of "strings", then this is correct, and you will need to change your function prototype to be expecting **char.

On a tangential note, if(words[i] == 'Wow') is not good for a number of reasons. First the ' character is used to denote a single character. Strings are enclosed with ". Second, string comparison cannot be accomplished with that sort of comparison. You need to use the strcmp like

if (strcmp(words[i], "Wow") == 0)

Not the answer you're looking for? Browse other questions tagged or ask your own question.