I am doing PSET 2 - Substitution and am trying to implement a check for every character of the key to be unique. For that I create a helper array key_check
, fill it with letters from the key one by one and check if the later I am trying to add to the helper array is already in there. For that, I am trying to use strstr
function.
Here is my code:
#include <ctype.h>
#include <stdlib.h>
#include <cs50.h>
#include <stdio.h>
#define _GNU_SOURCE
#include <string.h>
int main(int argc, string argv[])
{
// use a variable not to have to deal with argv[] array all the time
string key = (argv[1]);
// capitalize everything
for (int i = 0; i < strlen(key); i++)
{
key[i] = toupper(key[i]);
}
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
else if (strlen(key) != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
else
{
string key_check = malloc(strlen(key)+1);
for (int i = 0; i < strlen(key); i++)
{
// I compare if the same letter was already used before
if (!isalpha(key[i]) || strstr(key_check, key[i]) != NULL)
{
return 1;
}
// here I fill the letters to helper array one by one
key_check[i] = key[i];
}
}
return 0;
}
When I try to compile it, I get this error:
test.c:36:55: error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion]
if (!isalpha(key[i]) || strstr(key_check, key[i]) != NULL)
^~~~~~
&
/usr/include/string.h:350:58: note: passing argument to parameter '__needle' here
extern char *strstr (const char *__haystack, const char *__needle)
I don't understand why are integers involved in here and what it is trying to convert. key[i]
is supposed to return a single character from the key string, and if I replace key[i]
with a hardcoded letter, like 'A', it works. Trying to reduce variables and use argv[1][i]
instead also did not do it.
I've read the documentation on strstr
multiple times and tried to find a similar problem here, but did not find one about strstr specifically.
I am only on Week 2 right now, maybe there's something about pointers I don't know or understand right now, but I am completely clueless. Do you have any ideas what it is it doesn't like?