QMG
QMG

Reputation: 749

Array Arithmetic Issue in C

I have a C code in long file that is compiled using cc. But when I tried to compile on gcc it gives error. I took that particular code in small program and try to compile on cc but it failed over there.

Here is source:

#include <stdio.h>
int main (int argc, char **argv)
{
     char unsigned   FileName[100];
     char            test[100];
     FileName[strstr(FileName,test) - FileName] = 0;   
     return 0;
}

This line is causing the problem: FileName[strstr(FileName,test) - FileName] = 0;

error on CC is :

"foo.c", line 10: operands have incompatible types:
         int "-" pointer to unsigned char

and on gcc is :

foo.c:10: error: invalid operands to binary - Both are same.

But when I compile original file on CC it compiled and just give a warning. Like this:

"dbtprc.c", line 643: warning: argument #1 is incompatible with prototype:
        prototype: pointer to const char : "/usr/include/iso/string_iso.h", line 133
        argument : pointer to unsigned char
"dbtprc.c", line 643: warning: improper pointer subtraction

Can you please help why here it is giving warning "improper pointer subtraction" and sample program it is showing error?

Upvotes: 0

Views: 425

Answers (4)

Laurent G
Laurent G

Reputation: 3184

Don't you missed to include <string.h> ??

If yes, the prototype of strsrt is guessed and by default it returns an int, hence the invalid pointer operation.

Otherwise, it appears that the signedness mismatch is the cause of the warning/error. Use a (char*)cast before the two occurence of your table and it will go.

Upvotes: 1

karlphillip
karlphillip

Reputation: 93410

void * bar;
void * foo;
...
foo = bar + 1;

That's undefined behaviour, right there! You are referring to a memory location that wasn't even allocated.

EDIT:

Now you have another problem: even though you sucessfully declared both arrays, you failed to clean/initialize them. Only god knows what strstr() will return to you.

The problem you have compiling this code is that strstr() takes 2 const char* and you defined Filename as unsigned: char unsigned FileName[100];

char *strstr(const char *haystack, const char *needle);

Upvotes: 1

Sadique
Sadique

Reputation: 22823

Is there anything called Array Arithmetic in C? Read this:

Arrays are not Pointers.

And see how to use strstr().

Upvotes: 1

Bo Persson
Bo Persson

Reputation: 92241

An error or a warning is not much different, just showing how serious the compiler believes the issue is.

But why do you use unsigned char for the filename? That's in conflict with strstr which only handles char*, both for its parameter and return type.

That's what the compilers try to tell you, in different ways.

Upvotes: 0

Related Questions