Zetsuno
Zetsuno

Reputation: 95

String pointer as argument in C?

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')
...

Upvotes: 0

Views: 114

Answers (2)

Degustaf
Degustaf

Reputation: 2670

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)

Upvotes: 1

Fatih BAKIR
Fatih BAKIR

Reputation: 4735

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.

Upvotes: 3

Related Questions