Hello there,
I'm new to C programming and I have the following exercise to do:
"Consider an array v[0, 1,..., (n-1)] whose elements are strings. Remember that, in C a string is just an array of chars ending with the null character '\0'. So, you can suppose that v was declared this way: char *v[n]. Write a function that receives a string x and returns a index j in which x = v[j]. If this j doesn't exist, the function must return -1."
Here's what I did:
Code:
#include <stdio.h>
#include <string.h>
int contem(char string, char *v, int n) {
int i;
for (i = 0; i < 10; i++) {
if (strcmp(v[i], string) == 0) {
return i;
}
}
return -1;
}
main() {
char *v[10];
v[0] = "File";
v[1] = "Edit";
v[2] = "View";
v[3] = "Search";
v[4] = "Tools";
v[5] = "Documents";
v[6] = "Help";
v[7] = "Open";
v[8] = "Save";
v[9] = "Undo";
char string [100];
printf("String to search for: ");
gets(string);
int ret = contem(string, v, 10);
if (ret == -1) {
printf("The string is not in the array.");
return 0;
}
else printf("The string is at position: ", ret);
return 0;
}
I get the following warnings:
warning: passing argument 1 of 'strcmp' makes pointer from integer without a cast
warning: passing argument 2 of 'strcmp' makes pointer from integer without a cast
warning: passing argument 1 of 'contem' makes integer from pointer without a cast
warning: passing argument 2 of 'contem' from incompatible pointer type
What am I doing wrong? Does the array v must really be declared as a pointer?
Thanks in advance.
Regards,
Samir