ERROR: incompatible integer to pointer conversion assigning to 'string' (aka 'char *') from 'int'

Viewed 682

I created an array with 26 letters and I want to assign each elements to their ASCII values like that:

ASCII[0] = 65
ASCII[1] = 66

I'd already defined ASCII[0] as "A" in my array. So the result that I hope should be:

A = 65
B = 66

So what is the problem?Here is my code:

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

#define SIZE 26

int main(void)
{
    string ASCII[SIZE] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};

    for(int i=0; i<26; i++)
    {
        ASCII[i] = i+65;
    }
}
1 Answers

Unfortunately you've bitten by the stupid string typedef of the CS50 course. In cs50.h, string is a typedef for pointer to char. Ordinarily we do not use such a typedef at all in C - there is a lengthy debate about it in the libcs50 issues.

The i + 65 you do there is number, not a pointer - in this case, for a single character.

What you want is either:

char ASCII[SIZE] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

or

char ASCII[SIZE];
for (int i = 0; i < SIZE; i ++) {
    ASCII[i] = i + 65; // or even better: i + 'A'
}

either one will have any element of the 26-character array ASCII[i] equal to 65 + i.

Related