Error incompatible types in assignment

My C code #include #include #include "help.h" int test(int x, P *ut) { int point = 10; ut->dt[10].max_x = NULL; } int main(int argc, char** argv) { ...

My C code

#include <stdio.h>
#include <stdlib.h>
#include "help.h"

int test(int x, P *ut) {
    int point = 10;

    ut->dt[10].max_x = NULL;
}

int main(int argc, char** argv) {

    return (EXIT_SUCCESS);
}

my help.h file code

typedef struct{
    double max_x;
    double max_y;
}X;

typedef struct{
    X dt[10];
}P;

I got an error i.e

error: incompatible types in assignment

error comes in here

ut->dt[10].max_x = NULL;

can anybody help me.
thanks in advance.

asked Mar 31, 2010 at 10:18

ambika's user avatar

You are trying to set a double value to NULL, which even if compiles, is mixing two incompatible terms. (In some versions of the C class library NULL is defined simply as 0, in others as (void*)0 — in latter case you get an error for such code.)

Moreover, you try to access index 10 of an array of size 10, which is out of bounds — the elements are indexed from 0 to 9. So try this:

ut->dt[9].max_x = 0.0;

answered Mar 31, 2010 at 10:22

Péter Török's user avatar

Péter TörökPéter Török

113k31 gold badges268 silver badges329 bronze badges

0

I can see two problems in

ut->dt[10].max_x = NULL;
  • The index 10 is not valid, it
    should be 0-9
  • You are assigning a NULL value to a
    double. I guess you meant 0.0.

answered Mar 31, 2010 at 10:24

codaddict's user avatar

codaddictcodaddict

440k80 gold badges490 silver badges527 bronze badges

  1. max_x is of type double, NULL is of type (void *). What makes you think they are compatible?

    Try ut->dt[10].max_x = 0.0;

  2. Accessing dt[10] is out of bounds, array indexing starts at 0!

answered Mar 31, 2010 at 10:24

edgar.holleis's user avatar

edgar.holleisedgar.holleis

4,7131 gold badge23 silver badges27 bronze badges

0

Hi All,

I have reworked my code from my issue yesterday:

from typing import Dict, List, Union

ItemType = Dict[str, Union[str, float, int]]
ListItemType = List[ItemType]

HeaderType = Dict[str, Union[str, int, float]]
DataType = Dict[str, Union[HeaderType, ListItemType]]
ResultType = List[DataType]


def get_item_list() -> ListItemType:
    my_list = list()

    item_1: ItemType = {'param_1': 'string one',
                        'param_2': 3.4,
                        'param_3': 10}

    item_2: ItemType = {'param_1': 'string two',
                        'param_2': 55.4,
                        'param_3': 22}

    my_list.append(item_1)
    my_list.append(item_2)

    return my_list


def make_result() -> ResultType:
    list_1 = get_item_list()
    list_2 = get_item_list()

    header_1: HeaderType = {
        'name': 'header 1',
        'id': 1,
        'meta': 1.3
    }

    header_2: HeaderType = {
        'name': 'header 2',
        'id': 2,
        'meta': 2.6
    }

    data_1: DataType = {
        'head': header_1,
        'list': list_1
    }

    data_2: DataType = {
        'head': header_2,
        'list': list_2
    }

    result = list()
    result.append(data_1)
    result.append(data_2)

    return result


def process_result_1(result: ResultType):
    for res in result:
        res_list: ListItemType = res['list']
        for item in res_list:
            param_1 = item['param_1']
            param_2 = item['param_2']
            param_3 = item['param_3']

            print(param_1)
            print(param_2)
            print(param_3)
            print()


def process_result_2(result: ResultType):
    for res in result:
        res_list = res['list']
        for item in res_list:
            param_1 = item['param_1']
            param_2 = item['param_2']
            param_3 = item['param_3']

            print(param_1)
            print(param_2)
            print(param_3)
            print()


def main() -> None:
    res = make_result()
    process_result(res)


if __name__ == '__main__':
    main()

However, I still have some troubles with mypy in both process_result functions, for process_result_1 I’m getting the following error:

error: Incompatible types in assignment (expression has type "Union[Dict[str, Union[str, int, float]], List[Dict[str, Union[str, float, int]]]]", variable has type "List[Dict[str, Union[str, float, int]]]")
for process_result_2:

case_1.py:79: error: Incompatible types in assignment (expression has type "Union[str, float]", variable has type "str")
case_1.py:79: error: Invalid index type "str" for "Union[str, Dict[str, Union[str, float, int]]]"; expected type "Union[int, slice]"
case_1.py:80: error: Incompatible types in assignment (expression has type "Union[str, float]", variable has type "float")
case_1.py:80: error: Invalid index type "str" for "Union[str, Dict[str, Union[str, float, int]]]"; expected type "Union[int, slice]"
case_1.py:81: error: Incompatible types in assignment (expression has type "Union[str, float]", variable has type "int")
case_1.py:81: error: Invalid index type "str" for "Union[str, Dict[str, Union[str, float, int]]]"; expected type "Union[int, slice]"
case_1.py:91: error: Name 'process_result' is not defined

could someone give me a hint what I’m doing wrong here?

Thanks!

Best,
Alexey

Содержание

  1. incompatible struct types in casts/assignment?
  2. 4 Answers 4
  3. error: incompatible types in assignment of ‘char*’ to ‘char [20]’
  4. 4 Answers 4
  5. Simple C code, with vexing «incompatible types in assignment» error
  6. 3 Answers 3
  7. Incompatible Types in assignment to data structure in C
  8. 5 Answers 5
  9. Error incompatible types in assignment in c

incompatible struct types in casts/assignment?

This is a follow-up to this question.

I’m trying to avoid using an explicit typedef to copy one array to another through casts like this:

With gcc I’m getting arrcpy.c:8: error: incompatible types in assignment , however with Open Watcom it compiles fine (and works as I expect it, printing 1 through 3).

Is the gcc’s behavior per the standard or not? If it is, what’s the relevant chapter and section? I can’t understand why two identical type definitions struct aren’t the same (or compatible) in the gcc’s eyes.

EDIT: I know full well it’s a bad coding style. The question is about a different thing. I’m curious if there’s a logical rationale behind the gcc’s behavior, if it’s legit.

4 Answers 4

The gcc behavior is right, the types are two unrelated unnamed structures. Each of those structs, while having the same memory layout, have different names. If you really want to do that, then use a typedef.

The two struct definitions are not compatible:

Two types have compatible type if their types are the same. Additional rules for determining whether two types are compatible are described in 6.7.2 for type specifiers, in 6.7.3 for type qualifiers, and in 6.7.5 for declarators. Moreover, two structure, union, or enumerated types declared in separate translation units are compatible if their tags and members satisfy the following requirements.

The types aren’t the same. If they were declared in separate translation units, they would be compatible, however.

However, even if they were compatible, your code would still invoke undefined behavior, for at least two reasons:

  1. It uses the name «_» which is reserved.
  2. Accessing objects as a different type (except structs through char pointers, unions, etc.) isn’t allowed.

Источник

error: incompatible types in assignment of ‘char*’ to ‘char [20]’

I’m new to this C++ environment and I am having difficulty with my constructor. Here is my code:

When I compile it, it gives me an error saying incompatible types in assignment of char* to char[20] .

How can i fix this??

4 Answers 4

Your constructor argument nm is, actually, not an array! Yes, I know it looks like one, because you wrote char nm[20] . But, actually, it’s char* nm . That translation is performed automatically when you write an array type in a function parameter list. Yes, it’s stupid. Blame C.

So, the error message is telling you that you cannot assign a pointer to an array. Fair enough. Doesn’t really matter anyway, since the language also doesn’t let you assign arrays to arrays. Lol.

This is why, since 1998, we’ve had std::string to fix all these terrible problems:

If you must use an array, you can do this:

because std::array , introduced in 2011, is a handy wrapper around raw arrays that can be assigned (and don’t have that weird decay to pointers!).

«Ah, but my teacher told me to use raw arrays,» I hear you say. A shame, but we can fix that too. Either accept the array by reference, or take in a pointer to it (as you’re doing now! but this drops the dimension 20 from the type and makes things unsafe -.-) and do a manual copy of each element from the source to the destination. Certainly not ideal, but it may be what your teacher is expecting if this is homework:

Источник

Simple C code, with vexing «incompatible types in assignment» error

Just a simple program to get used to pointers. The program is supposed to put the contents of a portion of my memory into a character array in reverse order of how the memory is read. I.E. looking at descending memory address, and I want to store it in descending order in a character array.

My compiler keeps telling me: «error incompatible types in assignment»

On the line with the realloc function

What am I doing wrong? I seems to me that both «reverse», and the result of realloc should be pointers to type char?

EDIT: Sorry I mis-posted these as comments below

Thanks for the help, the first and second comment got it! I did have the required #includes, I just forgot to copy them into stack overflow. You were right, now I’m stuck on the non-null terminated strlen(). I’ll solve that one on my own. Thanks again!

I spoke too soon, it compiled alright, but there is a logic error. The while loop will execute one time. However, subsequent loops still fail, regardless of the initial value of i. The line that causes the failure is the the line that calls realloc

3 Answers 3

You can’t realloc memory that wasn’t malloced in the first place. You should declare reverse as «char *» and malloc it to start with.

This will get you going, but you really should think about reallocing in chunks, rather than one byte at a time. Oh, I didn’t bother to fix the fact that «reverse» is probably not null terminated when you try the strlen — I’ll leave that as an exercise for the reader.

  • You are compiling your C code with a C++ compiler. That’s why it thinks you need to cast the void* returned by realloc to a char*. The conversion would be legal in C.
  • You failed to include stdlib.h , so the compiler thinks realloc returns int

Edit

On reading your code again, the actual problem is that you are assigning to an array, which isn’t allowed to appear on the LHS of an assignment (isn’t an ‘lvalue’). It’s good that you accepted the other answer, though. It has some good advice.

You can’t realloc memory that wasn’t malloced in the first place.

Yes, definitely true, since in order to reallocate, malloc has to have have some additionnal information on the chunk of memory you manipulate (either through a block alocation table, or stored in the 4 bytes just before your pointer). But you could still write:

And you would not have a compiler error. You would still probably get a segfault at run time, though.

However, there is a fundamental difference in the way a C compiler treats

In the first case, tab is a pointer, of type char *, and is a lvalue like any normal variable. It probably resides in a register most of the time, or could be an address on the heap. In the second case, tab is an array, a constant, and is thus not an lvalue. It is probably replaced at assembly level by an address that points to the text section of your binary executable, where the data for the string «toto» resides.

Источник

Incompatible Types in assignment to data structure in C

i received this error when i compile my project.

My struct is something like this:

with a global variable:

Now, i’m assigning inside the program a parameter to the related parameter of the struct like this:

Also if I change the struct into this:

i receive a similar error:

Does anyone know where i’m wrong please? Thank you so much 🙂

5 Answers 5

Array name often decays to pointer to first element when it is a part of expression, except when an operand of sizeof or unary & operator.
newNode->tMat is of type double[4][4] . transformMatrix , when assigned to newNode->tMat , is converted to pointer to its first element, i.e of type double (*)[4] .

There are two things you can do:

Make tMat a pointer to Matrix4 .

C treats array objects differently from everything else 1 , so you cannot assign the contents of one array to the other using the = operator; IOW

To copy the contents of one (non-string) array to another, use the memcpy library function:

For strings, use either the strcpy or strncpy functions.

1. Except when it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an expression of type «N-element array of T » will be converted to an expression of type «pointer to T «, and the value of the expression will be the address of the first element in the array. The resulting expression is not a modifiable lvalue, and thus cannot be used as the target of an assignment. Read this essay, especially the section labeled «Embryonic C», for some insight into why this is the case.

Источник

Error incompatible types in assignment in c

**Edit I have now changed the way i am approaching this problem see second post

I am gett this error «vbays.cpp:74: error: incompatible types in assignment of ‘double’ to ‘double [1]’ « but I thought i was sending in my functions in the proper way that you guys showed me but i guess i still dont get the hang of it.

ERROR ON LINE 14

In function wmodel patameter model is declared as

that is it is a pointer to an object of type double[1].

So for example model[0] will be an array of type double[1].

you are trying to assign a scalar value to the array model[x]. Arrays have no the assignment operator.

That it would be more clear I will show an equivalent code to demonstrate what you are trying to do

The bolded statement is invalid.

ok i am slightly confused and since i have posted this i have decided to take another route.

now i am trying to pass the array in a different way. at first I didn’t realize that arrays are passed by reference by default.

Will my array still get all the math done to it then passed back to main or do i have to send a pointer?

If you defined the function the following way

double wmodel ( double model[], double f2, double f4, double f22 ,
double f42, double (*data)[3], int l);

then to call it you should write

wmodel( model, f2, f4 , conf2, conf4, data, l);

Источник

Polis_police

0 / 0 / 0

Регистрация: 20.02.2016

Сообщений: 7

1

20.02.2016, 23:46. Показов 18160. Ответов 13

Метки char, struct (Все метки)


Может быть, дело в том, что уже вечер и плохо соображаю, но никак не дается…

Код:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
    struct Camel{
        int horns, legs;
        char name[10];
        
        Camel *mother, *father;
    } cour, nari;
    
    cour.legs = 4;
    cour.name = "Loshak";
    nari.name = "Narciss";
    cour.mother = &nari;
 
    cout << "Camel's mother: " << cour.mother->name << endl;

Ожидаемый результат: Camel’s mother: Narciss
Фактический результат:
[Error] incompatible types in assignment of ‘const char [7]’ to ‘char [10]’ // строка 9
[Error] incompatible types in assignment of ‘const char [8]’ to ‘char [10]’ // строка 10

Вопрос: такое присвоение некорректно? Надо через strncpy() делать или что-то упустил?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Croessmah

Don’t worry, be happy

17781 / 10545 / 2036

Регистрация: 27.09.2012

Сообщений: 26,516

Записей в блоге: 1

20.02.2016, 23:49

2

C++
1
strcpy(cour.name, "Loshak") ;



1



0 / 0 / 0

Регистрация: 20.02.2016

Сообщений: 7

20.02.2016, 23:54

 [ТС]

3

Всё-таки strcpy, спасибо!

Хотя и не понятно, почему присваивание не работает.



0



3433 / 2812 / 1249

Регистрация: 29.01.2016

Сообщений: 9,426

21.02.2016, 00:57

4

Цитата
Сообщение от Polis_police
Посмотреть сообщение

Хотя и не понятно, почему присваивание не работает.

Почему, по-твоему, оно должно работать?



0



1378 / 405 / 144

Регистрация: 22.10.2014

Сообщений: 872

21.02.2016, 01:03

5

Цитата
Сообщение от Polis_police

(Прошу пнуть в нужную сторону)

Используйте std::string



0



0 / 0 / 0

Регистрация: 20.02.2016

Сообщений: 7

21.02.2016, 01:10

 [ТС]

6

Я считал, что должно работать, потому что:

а) в книжке, по которой я изучаю язык («Программирование на С/С++», Т.А. Павловская) такое присваивание указано в примере
б) опираясь на опыт РНР и ожидаемый результат (хотя это тут и не применимо, но привычки есть привычки)



0



3433 / 2812 / 1249

Регистрация: 29.01.2016

Сообщений: 9,426

21.02.2016, 01:20

7

Цитата
Сообщение от Polis_police
Посмотреть сообщение

такое присваивание указано в примере

Можно пример увидеть?



0



Polis_police

0 / 0 / 0

Регистрация: 20.02.2016

Сообщений: 7

21.02.2016, 01:25

 [ТС]

8

Текст учебника передрали здесь.

C++
1
2
3
4
5
6
7
8
9
struct Worker{
char fio[30];
int date, code;
double salary;
};
 
Worker worker, staff[100], *ps;
 
worker.fio = "Страусенко";



0



3433 / 2812 / 1249

Регистрация: 29.01.2016

Сообщений: 9,426

21.02.2016, 01:33

9

Цитата
Сообщение от Polis_police
Посмотреть сообщение

в книжке, по которой я изучаю язык («Программирование на С/С++», Т.А. Павловская) такое присваивание указано в примере

Книжку — в топку.



0



0 / 0 / 0

Регистрация: 20.02.2016

Сообщений: 7

21.02.2016, 01:35

 [ТС]

10

Если не сложно, объясните — почему не корректно такое присваивание. Из-за того, что char[10] — массив?



0



3433 / 2812 / 1249

Регистрация: 29.01.2016

Сообщений: 9,426

21.02.2016, 02:19

11

Из-за того, что name — имя массива (non-modifiable lvalue).



0



Polis_police

0 / 0 / 0

Регистрация: 20.02.2016

Сообщений: 7

21.02.2016, 22:35

 [ТС]

12

То есть вы хотите сказать, что когда пишешь

C++
1
2
int num;
num = 453;

то компилятор понимает, что я хочу переписать значение ячейки памяти на «12», а когда пишешь

C++
1
2
char stroka[10];
stroka = "somestring";

то он не понимает, что надо записать символов вместо существующих (и далее надо действовать с ним как с массивом или строковыми функциями) ?



0



nd2

3433 / 2812 / 1249

Регистрация: 29.01.2016

Сообщений: 9,426

21.02.2016, 23:15

13

Цитата
Сообщение от Polis_police
Посмотреть сообщение

то он не понимает, что надо записать символов вместо существующих (и далее надо действовать с ним как с массивом или строковыми функциями) ?

Компилятор понимает так, как ему предписано понимать. Имя массива — non-modifiable lvalue, значит нельзя ему что-то присваивать.
То что ты хочешь, делается так:

C++
1
2
3
4
char stroka[11] = "somestring"; // строковый литерал копируется в массив (не забыть место под '' выделить)
// или так
char stroka[11];
strcpy(stroka, "somestring");



1



0 / 0 / 0

Регистрация: 20.02.2016

Сообщений: 7

21.02.2016, 23:18

 [ТС]

14

Спасибо



0



Introduction to Data Types & Type Conversion

Variables are memory containers used to store information. In Java, every variable has a data type and stores a value of that type. Data types, or types for short, are divided into two categories: primitive and non-primitive. There are eight primitive types in Java: byte, short, int, long, float, double, boolean and char. These built-in types describe variables that store single values of a predefined format and size. Non-primitive types, also known as reference types, hold references to objects stored somewhere in memory. The number of reference types is unlimited, as they are user-defined. A few reference types are already baked into the language and include String, as well as wrapper classes for all primitive types, like Integer for int and Boolean for boolean. All reference types are subclasses of java.lang.Object [1].

In programming, it is commonplace to convert certain data types to others in order to allow for the storing, processing, and exchanging of data between different modules, components, libraries, APIs, etc. Java is a statically typed language, and as such has certain rules and constraints in regard to working with types. While it is possible to convert to and from certain types with relative ease, like converting a char to an int and vice versa with type casting [2], it is not very straightforward to convert between other types, such as between certain primitive and reference types, like converting a String to an int, or one user-defined type to another. In fact, many of these cases would be indicative of a logical error and require careful consideration as to what is being converted and how, or whether the conversion is warranted in the first place. Aside from type casting, another common mechanism for performing type conversion is parsing [3], and Java has some predefined methods for performing this operation on built-in types.

double myDouble = 9; // Automatic casting (int to double)
int myInt = (int) 9.87d; // Manual casting (double to int)
boolean myBoolean = Boolean.parseBoolean("True"); // Parsing with a native method (String to boolean)

System.out.println(myDouble);   // 9.0
System.out.println(myInt);      // 9
System.out.println(myBoolean);  // true

Incompatible Types Error: What, Why & How?

The incompatible types error indicates a situation where there is some expression that yields a value of a certain data type different from the one expected. This error implies that the Java compiler is unable to resolve a value assigned to a variable or returned by a method, because its type is incompatible with the one declared on the variable or method in question. Incompatible, in this context, means that the source type is both different from and unconvertible (by means of automatic type casting) to the declared type.

This might seem like a syntax error, but it is a logical error discovered in the semantic phase of compilation. The error message generated by the compiler indicates the line and the position where the type mismatch has occurred and specifies the incompatible types it has detected. This error is a generalization of the method X in class Y cannot be applied to given types and the constructor X in class Y cannot be applied to given types errors discussed in [4].

The incompatible types error most often occurs when manual or explicit conversion between types is required, but it can also happen by accident when using an incorrect API, usually involving the use of an incorrect reference type or the invocation of an incorrect method with an identical or similar name.

Incompatible Types Error Examples

Explicit type casting

Assigning a value of one primitive type to another can happen in one of two directions. Either from a type of a smaller size to one of a larger size (upcasting), or from a larger-sized type to a smaller-sized type (downcasting). In the case of the former, the data will take up more space but will be intact as the larger type can accommodate any value of the smaller type. So the conversion here is done automatically. However, converting from a larger-sized type to a smaller one necessitates explicit casting because some data may be lost in the process.

Fig. 1(a) shows how attempting to assign the values of the two double variables a and b to the int variables x and y results in the incompatible types error at compile-time. Prefixing the variables on the right-hand side of the assignment with the int data type in parenthesis (lines 10 & 11 in Fig. 1(b)) fixes the issue. Note how both variables lost their decimal part as a result of the conversion, but only one kept its original value—this is exactly why the error message reads possible lossy conversion from double to int and why the incompatible types error is raised in this scenario. By capturing this error, the compiler prevents accidental loss of data and forces the programmer to be deliberate about the conversion. The same principle applies to downcasting reference types, although the process is slightly different as polymorphism gets involved [5].

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

public class IncompatibleTypesCasting {

  public static void main(String... args) {
    double a = 10.5;
    double b = 5.0;
    System.out.println("a: " + a + "tb: " + b);

    int x = a;
    int y = b;
    System.out.println("x: " + x + "ty: " + y);
  }
}
IncompatibleTypesCasting.java:10: error: incompatible types: possible lossy conversion from double to int
    int x = a;
            ^
IncompatibleTypesCasting.java:11: error: incompatible types: possible lossy conversion from double to int
    int y = b;
            ^
2 errors

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

public class IncompatibleTypesCasting {

  public static void main(String... args) {
    double a = 10.5;
    double b = 5.0;
    System.out.println("a: " + a + "tb: " + b);

    int x = (int) a;
    int y = (int) b;
    System.out.println("x: " + x + "ty: " + y);
  }
}
a: 10.5 b: 5.0
x: 10   y: 5
Figure 1: Incompatible types when downcasting (a) error and (b) resolution

Explicit parsing

Parsing is a more complex process than type casting as it involves analyzing the underlying structure of a given data before converting it into a specific format or type. For instance, programmers often deal with incoming streams of characters, usually contained in a string that needs to be converted into specific types to make use of in the code. A common scenario is extracting numeric values from a string for further processing, which is where parsing is routinely used.

The main method in Fig. 2(a) declares the variable date which holds the current date as a String in the yyyy-MM-dd format. In order to get the year value into a separate variable it is necessary to “parse” the first 4 characters of the string, and this can be accomplished by splitting the string by specifying the “-” character as a delimiter and then accessing the first element (line 9 in Fig. 2(a)). With this, the year value has been successfully parsed and stored into a new variable. Attempting to increase the value of this new variable and store the resulting value in a separate int variable triggers the incompatible types error (line 10 in Fig. 2(a)). This is because even though the year has been isolated from the date and parsed into a new variable, it is impossible to perform arithmetic operations on a variable of type String. Therefore, it is necessary to represent this value as a numeric type. The best way to do this is to use Java’s built-in Integer::parseInt method which takes a String argument and converts it to an int (line 10 in Fig. 2(b)). (Note that if the given argument is not a valid integer value, this method will throw an exception.) Now that the year has been manually and explicitly parsed from the initial date string into an integer value that can be incremented, the program compiles and prints the expected message, as shown in Fig. 2(b).

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.time.LocalDate;

public class IncompatibleTypesParsing {

 public static void main(String... args) {
   String date = LocalDate.now().toString(); // "2021-12-21"
   String year = date.split("-")[0]; // "2021"
   int newYear = year + 1;
   System.out.println("Happy New Year " + newYear + "!");
 }
}
IncompatibleTypesParsing.java:10: error: incompatible types: String cannot be converted to int
    int newYear = year + 1;
                       ^
1 error

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.time.LocalDate;

public class IncompatibleTypesParsing {

  public static void main(String... args) {
    String date = LocalDate.now().toString();
    String year = date.split("-")[0];
    int newYear = Integer.parseInt(year) + 1;
    System.out.println("Happy New Year " + newYear + "!");
  }
}
Happy New Year 2022!
Figure 2: Incompatible types when parsing (a) error and (b) resolution

Incorrect type assignments

Sometimes, the incompatible types error can occur due to basic negligence, where the only mistake is an accidental mis-declaration of a variable’s type (Fig. 3(a)). In these instances, the issue is quite obvious and simply correcting the type declaration solves the problem (Fig. 3(b)).

(a)

package rollbar;

public class IncompatibleTypesAssignment {

 public static void main(String... args) {
   int greeting = "Merry Christmas!";
   System.out.println(greeting);
 }
}
IncompatibleTypesAssignment.java:6: error: incompatible types: String cannot be converted to int
    int greeting = "Merry Christmas!";
                   ^
1 error

(b)

package rollbar;

public class IncompatibleTypesAssignment {

 public static void main(String... args) {
   String greeting = "Merry Christmas!";
   System.out.println(greeting);
 }
}
Merry Christmas!
Figure 3: Incompatible types with incorrect assignment (a) error and (b) resolution

Incorrect method return types

A slightly less common but non-surprising occurence of the incompatible types error, especially when refactoring is involved, can be found in method return types. Namely, sometimes a method’s return statement ends up returning a value that doesn’t match the method’s declared return type (Fig. 4(a)). This issue has two possible remedies; either make the value returned match the return type (Fig. 4(b)), or change the method’s return type to match the actual value returned (Fig. 4(c)). And in the case of void methods (methods with no return type), one can simply get rid of the return statement if the return value is never used, as is the case with the example in Fig. 4.

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

public class IncompatibleTypesReturn {

 public static void main(String... args) {
   printGreeting();
 }

 static void printGreeting() {
   System.out.println("Happy Holidays");
   return true;
 }
}
IncompatibleTypesReturn.java:11: error: incompatible types: unexpected return value
    return true;
           ^
1 error

(b)

1
2
3
4
5
6
7
8
9
10
11
12
package rollbar;

public class IncompatibleTypesReturn {

 public static void main(String... args) {
   printGreeting();
 }

 static void printGreeting() {
   System.out.println("Happy Holidays");
 }
}
Happy Holidays!

(c)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

public class IncompatibleTypesReturn {

 public static void main(String... args) {
   printGreeting();
 }

 static boolean printGreeting() {
   System.out.println("Happy Holidays");
   return true;
 }
}
Happy Holidays!
Figure 4: Incompatible types with incorrect return type (a) error and (b)(c) two solutions

Incorrect imports and similarly named reference types

It is not uncommon to come across classes or other reference types with the same or a similar name. In fact, this happens even within the standard Java API, and can baffle many programmers, beginners and experts alike. One such case is the List class which represents one of Java’s main collection data structures [6]. This reference type can easily come into collision with another type of the same name, but from a different package. Namely, that’s the java.awt.List class that is part of Java’s built-in AWT API for creating graphical user interfaces [7]. All it takes is accidentally importing the wrong package, and the compiler immediately complains about the type mismatch, raising the incompatible types error, as demonstrated in Fig. 5(a). Fixing the import on line 5, as shown in Fig. 5(b), sorts things out.

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.util.ArrayList;
import java.util.Arrays;
import java.awt.List;

public class IncompatibleTypesList {

 public static void main(String... args) {
   List songs = new ArrayList<String>(Arrays.asList("Silent Night", "Deck the Halls", "Jingle Bells", "Winter Wonderland"));
   System.out.println(songs);
 }
}
IncompatibleTypesList.java:10: error: incompatible types: ArrayList<String> cannot be converted to List
    List songs = new ArrayList<String>(Arrays.asList("Silent Night", "Deck the Halls", "Jingle Bells", "Winter Wonderland"));
                 ^
1 error

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class IncompatibleTypesList {

 public static void main(String... args) {
   List songs = new ArrayList<String>(Arrays.asList("Silent Night", "Deck the Halls", "Jingle Bells", "Winter Wonderland"));
   System.out.println(songs);
 }
}
[Silent Night, Deck the Halls, Jingle Bells, Winter Wonderland]
Figure 5: Incompatible types incorrect reference type (a) error and (b) resolution

Popular external libraries are also prone to naming their reference types similarly, so whenever relying on such a library for a certain feature or functionality it is important to pick one, or be careful not to confuse one for another, if multiple libraries are already being used.

Fig. 6(a) shows an example of passing a JSON type object to a method as an argument. Here, the method printJson expects an argument of type JsonObject, but the calling method tries to pass in an instance of the similarly named JSONObject reference type, part of a different library altogether. This results in the incompatible types error being raised by the compiler, with the alert org.json.JSONObject cannot be converted to javax.json.JsonObject pointing to the erroneous method call. Swapping the inappropriate constructor call with an instance of the correct type solves the issue, as shown in Fig. 6(b).

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;

import org.json.JSONObject;
import javax.json.JsonObject;
import java.util.Map;

public class IncompatibleTypesJson {

  public static void main(String... args) {
    Map<String, Object> jsonMap = Map.of(
        "name", "Saint Nicholas",
        "nicknames", new String[]{"Santa Claus", "Father Christmas"},
        "location", "North Pole"
    );

    JsonObject json = Json.createObjectBuilder(jsonMap).build();

    printJson(json);
}

  static void printJson(JSONObject jsonObject) {
    System.out.println(jsonObject.toString(4));
  }
}
IncompatibleTypesJson.java:18: error: incompatible types: 
javax.json.JsonObject cannot be converted to org.json.JSONObject
    printJson(json);
              ^

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;

import javax.json.Json;
import javax.json.JsonObject;
import java.util.Map;

public class IncompatibleTypesJson {

  public static void main(String... args) {
    Map<String, Object> jsonMap = Map.of(
        "name", "Saint Nicholas",
        "nicknames", new String[]{"Santa Claus", "Father Christmas"},
        "location", "North Pole"
    );

    JSONObject json = new JSONObject(jsonMap);

    printJson(json);
  }

  static void printJson(JSONObject jsonObject) {
    System.out.println(jsonObject.toString(4));
  }
}
{
    "name": "Saint Nicholas",
    "location": "North Pole",
    "nicknames": [
        "Santa Claus",
        "Father Christmas"
    ]
}
Figure 6: Incompatible types incorrect reference type (a) error and (b) resolution

Fig. 6 also serves as an example to show how the incompatible types error is, in fact, a generalization of the method X in class Y cannot be applied to given types error explored in [4]. Depending on the specific compiler that is being used and its configuration settings, either of these errors could be triggered in this kind of scenario.

Summary

As a strongly typed language, Java has strict rules regarding data types and how they interoperate. These rules affect variable assignment, method invocation, return values, etc. This makes Java code verbose, but at the same time quite secure, as it allows for many errors to be detected during compilation. One such error is the incompatible types error, which is directly tied to Java’s type system. This article provides some background into Java types and dives into the symptoms and causes behind the incompatible types error, by presenting a series of relevant examples tailored to bring clarity in understanding and successfully managing this error.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

References

[1] R. Liguori and P. Liguori, 2017. Java Pocket Guide, 4th ed. Sebastopol, CA: O’Reilly Media, pp. 23-46.

[2] W3schools.com, 2021. Java Type Casting. Refsnes Data. [Online]. Available: https://www.w3schools.com/java/java_type_casting.asp. [Accessed: Dec. 18, 2021]

[3] D. Capka, 2021. Lesson 3 — Variables, type system and parsing in Java, Ictdemy.com. [Online]. Available: https://www.ictdemy.com/java/basics/variables-type-system-and-parsing-in-java. [Accessed: Dec. 19, 2021]

[4] Rollbar, 2021. How to Fix Method/Constructor X in Class Y Cannot be Applied to Given Types in Java, Rollbar Editorial Team. [Online]. Available: https://rollbar.com/blog/how-to-fix-method-constructor-in-class-cannot-be-applied-to-given-types-in-java/. [Accessed: Dec. 21, 2021]

[5] W3schools.com, 2021. Java Type Casting. Refsnes Data. [Online]. Available: https://www.w3schools.com/java/java_type_casting.asp. [Accessed: Dec. 21, 2021]

[6] Oracle.com, 2021. Lesson: Implementations (The Java™ Tutorials > Collections). [Online]. Available: https://docs.oracle.com/javase/tutorial/collections/implementations/index.html. [Accessed: Dec. 21, 2021]

[7] Oracle.com, 2020. Package java.awt (Java SE 15 & JDK 15). Oracle and/or its affiliates [Online]. Available: https://docs.oracle.com/en/java/javase/15/docs/api/java.desktop/java/awt/package-summary.html. [Accessed: Dec. 21, 2021]

I am getting an error message «incompatible types in assignment of ‘int’ to ‘int [7]’ on lines 49 & 52

Here is my whole code, writing a battleship game that’s to be played against a computer

#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <ctime>

using namespace std;
char box[7][7];

void drawBoard()
{
cout<<» | 1 | 2 | 3 | 4 | 5 | 6 | 7 |»<<endl;
cout<<«—+—+—+—+—+—+—+—+»<<endl;
cout<<«A |»<<box[0][1]<<» |»<<box[0][2]<<» |»<<box[0][3]<<» |»<<box[0][4]<<
» |»<<box[0][5]<<» |»<<box[0][6]<<» |»<<box[0][7]<<» |»<<endl;
cout<<«—+—+—+—+—+—+—+—+»<<endl;
cout<<«B |»<<box[1][1]<<» |»<<box[1][2]<<» |»<<box[1][3]<<» |»<<box[1][4]<<
» |»<<box[1][5]<<» |»<<box[1][6]<<» |»<<box[1][7]<<» |»<<endl;
cout<<«—+—+—+—+—+—+—+—+»<<endl;
cout<<«C |»<<box[2][1]<<» |»<<box[2][2]<<» |»<<box[2][3]<<» |»<<box[2][4]<<
» |»<<box[2][5]<<» |»<<box[2][6]<<» |»<<box[2][7]<<» |»<<endl;
cout<<«—+—+—+—+—+—+—+—+»<<endl;
cout<<«D |»<<box[3][1]<<» |»<<box[3][2]<<» |»<<box[3][3]<<» |»<<box[3][4]<<
» |»<<box[3][5]<<» |»<<box[3][6]<<» |»<<box[3][7]<<» |»<<endl;
cout<<«—+—+—+—+—+—+—+—+»<<endl;
cout<<«E |»<<box[4][1]<<» |»<<box[4][2]<<» |»<<box[4][3]<<» |»<<box[4][4]<<
» |»<<box[4][5]<<» |»<<box[4][6]<<» |»<<box[4][7]<<» |»<<endl;
cout<<«—+—+—+—+—+—+—+—+»<<endl;
cout<<«F |»<<box[5][1]<<» |»<<box[5][2]<<» |»<<box[5][3]<<» |»<<box[5][4]<<
» |»<<box[5][5]<<» |»<<box[5][6]<<» |»<<box[5][7]<<» |»<<endl;
cout<<«—+—+—+—+—+—+—+—+»<<endl;
cout<<«G |»<<box[6][1]<<» |»<<box[6][2]<<» |»<<box[6][3]<<» |»<<box[6][4]<<
» |»<<box[6][5]<<» |»<<box[6][6]<<» |»<<box[6][7]<<» |»<<endl;
cout<<«—+—+—+—+—+—+—+—+»<<endl;
}
//^ this looks really messy, its not that bad just prints the game board and labels each spot
//looks like this:
// | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
//—+—+—+—+—+—+—+—+
//A |

void shipPlacement()
{
int ShipPlacement[7][7];
int r, c;
srand(time(NULL));
for(int c=0; c<8; c++)
{
ShipPlacement[c]=((rand()%7)+1);
for(int r=0; r<8; r++)
{
ShipPlacement[r]=(rand()%7);
}
}
cout<<ShipPlacement;
}

int main()
{
drawBoard();
shipPlacement();
return 0;
}

line 49—> ShipPlacement[c]=((rand()%7)+1);
line 52—> ShipPlacement[r]=(rand()%7);

Last edited on

ShipPlacement[c] is an array of seven int values.

((rand()%7)+1) is a single int.

What you’re doing makes no sense. You’ve got an array of seven int values, and you’re saying «this array of seven int values is to be set equal to this one, single int value». Makes no sense.

Hello richieH1997,

Welcome to the forum.

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

Until I can load up the program and see what is happening it is hard to follow your code. Just add code tags to what yu have will not indent the code as it needs to be.

Soon as figure this out I will let you know.

Andy

Hello richieH1997,

In the function «shipPlacement» you define the array «ShipPlacement» as a 2D array. IMHO I would call this backwards. i would use the capital «S» for the function name and the lower case «s» for the variable name.

Anyway ShipPlacement[c]=((rand()%7)+1); «ShipPlacement» is a 2D array and you are only using one dimension to store your result. The reason this does not work is because the result of «rand» needs to be stored in the second dimension not the first.

«srand» should be near the beginning of main because you only need to call it once. Should your game play again as is «srand» would be called again when «shipPlacement» is called and the numbers may not be as random as you might think.

((rand() % 7) + 1) this will miss the number zero. This may work, but for an array that starts at zero you would be missing an entire row or column.

To set a 2D array you will need an outer for loop to control the row and the inner for loop, that you have, to control the columns.

I offer this suggestion for your program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <ctime>

constexpr unsigned int MAXROW{ 7 };
constexpr unsigned int MAXCOL{ 7 };

void shipPlacement(int ShipPlacement[MAXROW][MAXCOL])
void drawBoard(char box[MAXROW][MAXCOL])


int main()
{
	char box[MAXROW][MAXCOL];
	int ShipPlacement[MAXCOL][MAXCOL];

	srand(time(NULL));  // <---Needs called only once. Best done here.

	drawBoard();
	shipPlacement();


	return 0;
}

// Functions here 

Hope that helps,

Andy

Thank you andy, I realize my mistake thanks so much!

Side note I haven’t learned in my c++ class what «constexpr» is or «unsigned» if you could just explain what those do that’d be greatly appreciated!

Hello richieH1997,

You are welcome.

If you are finished be sure to green check the thread so others will know.

Andy

constexpr (since C++11):
http://en.cppreference.com/w/cpp/language/constexpr

unsigned:
http://en.cppreference.com/w/cpp/language/types

A simpler explanation of unsigned. An integer type that can not hold any negative values.

For example:

int

is a signed type. It can hold negative and positive values. -1 or 125.

To understand the differences between signed and unsigned run this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <limits>

int main()
{
   std::cout << "typetlowest()tmin()ttmax()nn";

   std::cout << "intt"
      << std::numeric_limits<int>::lowest() << 't'
      << std::numeric_limits<int>::min() << 't'
      << std::numeric_limits<int>::max() << 'n';

   std::cout << "nunsigned intt"
      << std::numeric_limits<unsigned int>::lowest() << 't'
      << std::numeric_limits<unsigned int>::min() << 't'
      << std::numeric_limits<unsigned int>::max() << 'n';
}

type    lowest()        min()           max()

int     -2147483648     -2147483648     2147483647

unsigned int    0       0       4294967295

int

can be written as

signed int

,

unsigned int

can be written as

unsigned

.

I use eclipse for my coding, and it says the program gave has errors , its probable just eclipse i guess, never seen the std:: stuff.

also constexpr didn’t work, i changed it to just const int MAXROW[7];

Your compiler is either unable to use a newer C++ standard, or you haven’t set the language standard to make

constexpr

available.

I don’t use Eclipse, so I don’t know what the problem might be.

never seen the std:: stuff.

using namespace std;

will do that. It is considered a bad thing to do.
https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice.

You might want to learn about the C++ random library.
http://en.cppreference.com/w/cpp/numeric/random

srand()/rand()

have serious drawbacks.
http://cpp.indi.frih.net/blog/2014/12/the-bell-has-tolled-for-rand/

Hello richieH1997,

As FurryGuy said «constextp» is from C++11 on, but «const» will work just as well. What this is likely saying is that your compiler and header files need upgraded to at least cover the C++11 standards.

In short the unsigned means that the variable can only hold positive numbers. This is useful because there are many functions that return an «unsigned int» and the subscript of any type of array can only have a positive number. Using «unsigned» just makes sure that what is going into the variable is a positive number.

Hope that helps,

Andy

const

tells the compiler you, the programmer, won’t be trying to change an object, a variable. If you do, the compiler slaps your hand and says, «no, no no.»

constexpr

expands what

const

can do to functions.

1
2
3
4
constexpr int factorial(int n)
{
    return n <= 1 ? 1 : (n * factorial(n - 1));
}

Any use of the function is evaluated at compile-time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

constexpr int factorial(int n)
{
   return n <= 1 ? 1 : (n * factorial(n - 1));
}

int main()
{
   // this is evaluated at compile-time, not run-time
   int fact4 = factorial("A");

   std::cout << "4!: " << fact4 << 'n';
}

Error	C2664	'int factorial(int)': cannot convert argument 1 from 'const char [2]' to 'int'
Error (active)	E0167	argument of type "const char *" is incompatible with parameter of type "int"

So you can find possible problems at compile-time instead of when your program is running.

Last edited on

Topic archived. No new replies allowed.

table = fizz(table);

Что сделать-то хотел?
Если проинициализировать массив значением которое вернула fizz, нужно было просто проинициализировать его в этой функции.
Если поменять область памяти на которую указывает table, то нужно было сделать table указателем.

Почему при передаче table в fizz struct Item[100] преобразуется в struct Item *table, а при присваивании — нет?

Потому что массив — это синтаксис для статического выделения памяти на стеке, в области данных или в структурах. Имя массива — это имя этого блока памяти, а его адрес — адрес этого блока. Поэтому имя массива можно легко сконвертировать в адрес. Но если бы язык давал возможность менять адрес массива с помощью присваивания его имени, массив помимо своих элементов должен бы был содержать дополнительный указатель. Получился бы странный, сложный класс объектов, соединяющий в себе свойства массива и указателя. Поскольку язык С — простой язык, у вас есть отдельно массивы и отдельно указатели, а сложный тип можно сделать самому.

The issue is with flexible array int _teamIRCodes[]; This is an old technique which I don’t recommend. But if you want to use it, you need you use malloc to create a class object, adding on enough space for the array:

// Allocate space for the class AND the array
Gun *gun = (Gun *)malloc(sizeof(Gun) + sizeof(teamIRCodes));

However, this does not call the ctor, and you still have to manually copy the data:

for(int i = 0; i < (sizeof(teamIRCodes) / sizeof(teamIRCodes[0])); i++) {
    gun->_teamIRCodes[i] = teamIRCodes[i];
}

I think it’s much simpler to use a pointer:

int* _teamIRCodes;

Then you can make your ctor:

Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
    _teamIRCodes = new int[numberOfCodes];
    // memcpy does the same thing as the for loop - copies the array
    memcpy(_teamIRCodes, teamIRCodes, sizeof(teamIRCodes[0]) * numberOfCodes);
}

And don’ forget to add a dtor:

~Gun() {
    delete [] _teamIRCodes;
}

Or, if teamIRCodes is persistent throughout the lifetime of the object, you can just use a pointer to it:

 class Gun {
     public:
     int *_teamIRCodes;
     int _numberOfCodes;
     Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
         _teamIRCodes = teamIRCodes;
         _numberOfCodes = numberOfCodes;
   };

(Maybe this is an Arduino thing as this is the 2nd flexible array question I’ve seen today).

Понравилась статья? Поделить с друзьями:
  • Error incompatible types got single expected smallint
  • Error incompatible types got real expected smallint
  • Error incompatible types got extended expected smallint
  • Error incompatible types got extended expected longint
  • Error incompatible types got double expected smallint