0

I think I might be misunderstanding some basic things about strings because I'm really struggling to get the salt in crack. I'm getting compile errors from the below code. I've also tried making the elements in the salt string argv[1][0] and argv[1][1].

Going back through the lecture 2 materials didn't really have any answers for me. I'm guessing that I need to go ahead to the next lecture to learn about pointers and malloc and stuff based upon all of the other code I've seen that actually does what I'm trying to do. But would love any explanation anyone could give as to why my code doesn't work.

Code:

#include <cs50.h>
#include <stdio.h>
#include <crypt.h>
#include <string.h>

int main(int argc, string argv[])
{
    // Checks that the keyword is valid
    if (argc != 2)
    {
        printf("Invalid Password!");
        return 1;
    }
    string hash = argv[1];
    string salt[3];
    salt[0] = hash[0]; 
    salt[1] = hash[1];
    salt[2] = '\0';
    printf("%s\n %s\n", hash, salt);

Errors:

crack.c:16:13: error: incompatible integer to pointer conversion assigning to 'string'
      (aka 'char *') from 'char'; take the address with & [-Werror,-Wint-conversion]
    salt[0] = hash[0]; 
            ^ ~~~~~~~
              &
crack.c:17:13: error: incompatible integer to pointer conversion assigning to 'string'
      (aka 'char *') from 'char'; take the address with & [-Werror,-Wint-conversion]
    salt[1] = hash[1];
            ^ ~~~~~~~
              &
crack.c:18:15: error: expression which evaluates to zero treated as a null pointer constant
      of type 'string' (aka 'char *') [-Werror,-Wnon-literal-null-conversion]
    salt[2] = '\0';
              ^~~~
crack.c:19:31: error: format specifies type 'char *' but the argument has type 'string *'
      (aka 'char **') [-Werror,-Wformat]
    printf("%s\n %s\n", hash, salt);
                 ~~           ^~~~
2
  • 1
    Did you mean to declare salt as an array (length 3) of strings? Based on the rest of the code, perhaps you meant salt to be an array (length 3) of chars, i.e. char salt[3] that will be treated as a string by terminating with a null. – DinoCoderSaurus May 11 '19 at 18:59
  • I did! I knew it was a simple understanding issue I had with strings. Really helpful though. Thanks! – pwhalen May 11 '19 at 22:08
1

argv [1] is, in effect, a string, however the statement:

string salt[3];

It is incorrect. What are you really saying? Keep in mind that the variable of type string does not exist in c, it is a typedef of char *, a pointer of type char, which is the type of variable that is normally used to handle strings. So your statement really says that you declare an array of pointers to char type, analyze the errors now and you will notice it, as correctly pointed @DinoCoderSaurus you must declare an array of type char simply.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .