0

I've tried this over and over and can't get this right. This is only a snippet of my code. I keep on getting this error:

"testcode.c:21:31: error: incompatible integer to pointer conversion assigning to 'string' (aka 'char *') from 'char'; take the address with & [-Werror,-Wint-conversion] ciphertext[x] = sub[x]; ^ ~~~~~~ &"

I've seen other people do similar, and it compiles for them, so I'm not understanding why it's giving me this error. Thanks for any insight!

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main(int argc, string argv[])
{
    string plain = get_string("plaintext: ");
    string key = argv[1];
    string Ualphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    // Using plaintext, get position of alphabet
    string ciphertext[strlen(plain)];
    for (int i = 0, n = strlen(plain); i < n; i++)
    {
        for (int x = 0; x < strlen(plain); x++ )
        {
            if (plain[x] == Ualphabet[i])
            {
                ciphertext[x] = key[x];
                printf("%c", ciphertext[x]);
            }
        }

1 Answer 1

0

Here lies the problem:

string ciphertext[strlen(plain)];

Let's say that strlen(plain) = 10. This declaration isn't creating a string of length 10, it's creating an array of 10 strings with length 0.

However, it doesn't look like there's an easy way to do what you want with the cs50 type of string. (string is supposed to be a tool to get students started without having to learn everything at once before writing the first couple programs.) So, time to learn how to use char. Your code was on the right track. It does work this way:

char ciphertext[strlen(plain)+1];

This will allocate a char array of single chars, aka, a string. You'll learn more about this soon or you can research it with google. ;-)

Notice the "+1" in there. strlen() will count the number of real chars in a string, but you almost always MUST add 1 more for the end of string marker, \0 to be added. Functions like strlen and printf depend on finding that marker.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Ahh. Got it. I got some other stuff to fix, but at least it compiled. Thank you, Cliff!
    – KidAmulet
    May 13, 2022 at 2:25

You must log in to answer this question.

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