Max Jones
Max Jones

Reputation: 135

Getting rid of warning: integer from pointer without a cast [-Wint-conversion] with working code

I am working on a tiny bit of code that will take in a text document and "encode" it by shifting all chars by 5 (ascii).

The code is working, but I am getting an error and was wondering how I would get rid of it.

I am getting this warning:

warning: initialization makes integer from pointer without a cast [-Wint-conversion]
            char new_ch = *ch + 5;

The relevant portion of my code is :

        char *ch[0];
        // Reads and writes output
        while (read(old_file, current_char, 1) == 1) {
           char new_ch = *ch + 5;
           write(new_file, &new_ch, 1);
        }

Upvotes: 0

Views: 487

Answers (3)

0___________
0___________

Reputation: 67820

char *ch[0]; defines the array of pointers to char which has size 0. If you try to dereference it you will invoke the UB.

you need to

    char ch[some_size_larger_than_zero];
    // Reads and writes output
    while (read(old_file, current_char, 1) == 1) {
       char new_ch = *ch + 5;
       write(new_file, &new_ch, 1);
    }

Upvotes: 1

P.P
P.P

Reputation: 121407

The problem is with ch; it's an array of pointers.

If you are reading one char at a time, you would instead need:

char ch;

and make your read calls with:

if (read(fd, &ch, 1) < 0) {
    /* error */
}

i.e. just like how you use new_ch when calling write:

    char ch;
    // Reads and writes output
    while (read(old_file, &ch, 1) == 1) {
       char new_ch = ch + 5;
       write(new_file, &new_ch, 1);
    }

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409384

C doesn't have dynamic arrays, you attempt to create an array of zero elements (which is invalid) where each element is a pointer.

And this array of pointers is what leads to your error as the expression *ch is the same as ch[0], which is a pointer. Adding 5 to that pointer will just make it point a little further on in memory but it's still a pointer. Then you assign this pointer (ch[0] + 5) to the single char variable new_ch.

So there are multiple problems in your code, but unfortunately only one of them seems to lead to a warning being generated by the compiler.

Exactly how to solve your problem and get rid of the warning depends on what you're really trying to do, but very likely you're supposed to make ch a single character, as in

char ch;

and then use a pointer to that (gotten by &ch) as the destination for the read call:

read(old_file, &ch, 1)

Then you could add 5 to that single character:

char new_ch = ch + 5;

and write it to the new file.

Upvotes: 2

Related Questions