la_
la_

Reputation: 51

fopen incompatible type char (*)[9] instead of char(*) in C

My program in C reads data in a file in order to initialise variables but it won't open the file. It fails when it reaches fopen. Xcode outputs the following warning for both fopen and printf. I understand the error but I don't know how to correct it, I tried many tricks but it won't do, can anyone help me out ? I just want my program to open Try1.txt.

Incompatible pointer types passing 'char (*)[9]' to parameter of type const char*'

So this is the code inside my main function :

FILE *infile = NULL;
const char infilename [] = "Try1.txt";

infile = fopen(&infilename, "r");
if (infile == NULL)
{
    printf("Failed to open file: %s\n", &infilename);
    return 1;
}

Note that the program stops before reaching the if loop because it never prints. I tried to initialise the size and to add '\0' at the end of my string too.

Upvotes: 0

Views: 591

Answers (2)

sampathsris
sampathsris

Reputation: 22290

Problem

&infilename is a pointer to the array, which means it is a pointer to an object of type char (*)[9].

But, infilename will be a pointer of type char (*), which points to the first element of the array.

Fix

infile = fopen(infilename, "r");

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409412

It's because of &infilename, which gives you a pointer to the array of characters. Drop the address-of operator and it will work.

Upvotes: 5

Related Questions