Меню

Different levels of indirection ошибка

This code is giving me this error, which I don’t understand. I can’t even run the program. Can you help me to fix this error, please? If you don’t understand anything in the code, say it.

error C2040: 'CancelarPedido' : 'ppedido (ppedido)' differs in levels of indirection from ‘int ()’

printf("nIntroduza opcao:");
    scanf("%d",&opc);

    switch(opc){
        case 1: lista = NovoPedido(lista);break;
        case 2: lista = CancelarPedido(lista);break;
        case 3: printf("Falta implementar a funcao.");break;
        case 4: printf("Falta implementar a funcao.");break;
    }
    }while(opc!=5);

    return lista;
}


ppedido CancelarPedido(ppedido lista)
{
    ppedido actual, anterior = NULL;

    char id[5];

    actual = lista;

    if(lista == NULL)
        printf("nNao ha pedidos na fila de espera...");
    else
    {
        printf("nIntroduza o ID do pedido que pretende cancelar: ");
        scanf("%s", id);

        while(actual != NULL && ((strcmp(actual->id, id)) != 0)){
            anterior = actual;
            actual = actual->prox;
        }
        if(actual == NULL){
            printf("nERRO - Nao existe nenhum pedido com o ID introduzido.");
            return lista;
        }
        if(anterior == NULL){
            lista = actual->prox;
            printf("nPedido cancelado com sucesso...");
        }
        else{
            anterior->prox = actual->prox;
            printf("nPedido cancelado com sucesso...");
        }
        free(actual);
        return lista;
    }
}

Jongware's user avatar

Jongware

22k8 gold badges52 silver badges99 bronze badges

asked Jun 23, 2012 at 4:23

Marco's user avatar

8

You are calling CancelarPedido before you declared it. You need to reorder the code or add a forward declaration for CancelarPedido.

Without a declaration of CancelarPedido in scope, it defaults to int CancelarPedido(). You get the error message because lista is declared to be a pointer but CancelarPedido is declared to return an int.

answered Jun 23, 2012 at 4:32

Jim Balter's user avatar

Jim BalterJim Balter

15.9k3 gold badges43 silver badges66 bronze badges

4

  1. 09-10-2001


    #1

    Garfield is offline


    the Corvetter


    Levels of Indirection???

    Every once in a while, I get this same warning message that causes DOS to crash and I don’t know what to do about it. I’ll give you the code, and then the warning:

    Code:

    #include <stdio.h>
    
    char vName[] = "John Smith";
    char *const pName = &vName;
    
    char vDate[] = "9/10/01";
    const char *pDate = &vDate;
    
    int main()
    {
        printf("Name = %s Date = %s", *pName, *pDate);
        *pName = "George Washington";
        pDate = "6/10/01";
        printf("Name = %s Date = %s", *pName, *pDate);
        return (0);
    }

    That’s the code. And the warning message is «‘const char *’ differes in levels of indirection». What exactly would a level of indirection be? Well, this warning is causing the program to crash and it is getting to me. Thanks.


  2. 09-10-2001


    #2

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    Well there are quite a few broken indirections in your code.

    Code:

    char vName[] = "John Smith";
    char *const pName = vName;  // this is a constant pointer
    char vDate[] = "9/10/01";
    const char *pDate = vDate;  // this is a pointer to a constant
    int main()
    {
        printf("Name = %s Date = %s", pName, pDate);
        pName = "George Washington";    // it's constant, so this assignment is illegal
        pDate = "6/10/01";
        printf("Name = %s Date = %s", pName, pDate);
        return (0);
    }

    > What exactly would a level of indirection be?
    It’s a count of how many *’s you have to go through to get to the real data.

    > Well, this warning is causing the program to crash and it is getting to me.
    Fix the code then — this is one of the warnings you shouldn’t be ignoring.


  3. 09-10-2001


    #3

    Garfield is offline


    the Corvetter


    Well, I have just gotten a reply from another C message board and I think you two have different explanations. He said that I was trying set set a string to a pointer. The array of a pointer, he said, is memory so you can’t set an array of characters to it. He said that I would have to do the strcopy function to put another string into it. Do you agree? I don’t really understand what you are saying.

    When you say the level of indirection is «a count of how many *’s you have to go through to get to the real data», what do you mean? Thanks.


  4. 09-10-2001


    #4

    Garfield is offline


    the Corvetter


    I think I just realized something. When you say the number of *’s to get to the data, you mean the number of pointers, right? So, where was my error? I read that I can change the pointer to a constant string (for example) and that isn’t working with the string, but the constant. Now that I think of it, it doesn’t really make sense.

    Take a look at my first post. So, you’re saying if you have:

    Code:

    const char *pPointer = &vVar;

    that I can’t change either the pointer (pPointer = ‘A’) or I can’t change what it points to (*pPointer = ‘A’)? Is there a difference between my two examples (pPointer = ‘A’ and *pPointer = ‘A’)? But if I have this:

    Code:

    char *const pPointer = &vVar;

    then I can legally do the changes (pPointer = ‘A’ and *pPointer = ‘A’) because the const pointer only means that that pointer can only point to that char address, right? Thanks.


  5. 09-11-2001


    #5

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    char vName[] = «John Smith»;
    char *pPointer = &vName;

    Ignoring the const for a moment, this code has incompatible types.
    An array name by itself (vName) has the same type as a pointer to any element of the array (&vName[x]), and specifically the same value as a pointer to the first element of the array (&vName[0]).
    So you would have
    char vName[] = «John Smith»;
    char *pPointer = vName;

    The &vName is a pointer to the whole array, not a pointer to the first element (it’s likely to be the same value as a pointer to the first element, but the type is totally different)
    To make this valid, you need a different type of pointer
    char hello[] = «hello»;
    char (*arr)[6] = &hello;
    Note that this isn’t an array of 6 pointers to char, its a pointer (singular) to an array of 6 characters.

    The const keyword can be used as follows
    char hello[] = «hello»;
    char world[] = «world»
    const char *a = hello;
    char * const b = hello;

    a is a pointer to a constant char — this means you can modify a (say a=world), but you can’t modify what a points to (say a[0] = ‘f’ would be illegal).

    b is a constant pointer to char — this means you cannot change b, but you can change b[0]

    const char * const c = hello;
    means you cannot modify c or c[0]

    > Do you agree?
    No — what you are trying to do is perfectly valid, once you’ve sorted out some of the use of & and * in a place or two.


  6. 09-11-2001


    #6

    Garfield is offline


    the Corvetter


    So, how come that my code was invalid? I had right syntax (I think). I had this:

    Code:

    char first[10];
    const char *ptrfirst = &first;
    char last[10];
    char *const ptrlast = &last;
    
    int main()
    {
        ptrfirst = "Thomas"; /* Is this legal?  I'm changing the pointer, not the object it points to, right? */
        *ptrlast = "Jefferson"; /* Is this legal?  I'm changing the object that the pointer points to, not the pointer, right?
         
        return (0);
    }

    Isn’t this code right? If not, why? Thanks!


  7. 09-11-2001


    #7

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    > const char *ptrfirst = &first;
    Recall my previous post about the difference between first and &first.
    The levels of indirection are the same, but the pointers are of an incompatible type
    So
    &nbsp; const char *ptrfirst = first;

    > ptrfirst = «Thomas»;
    Nothing wrong here — ptrfirst is a (variable) pointer to a const char, so assigning the pointer to point to another char is valid.
    «string» has the type const char *
    So you have these types in the assignment.
    &nbsp; const char * = const char *
    so all is well

    > *ptrlast = «Jefferson»;
    I get this — warning: assignment makes integer from pointer without a cast
    What you’re trying to do here is take a pointer (to the string), cast it to an integer and truncate it so it fits inside a single character.
    You have these types in the assignment.
    &nbsp; char = const char *
    a char just being a small integer

    If you tried this
    > ptrlast = «Jefferson»;
    I get this — warning: assignment of read-only variable `ptrlast’
    Althought the types match, you’ve said that ptrlast is a constant, so it complains when you try and modify the pointer.

    To update this, you would need something like
    &nbsp; strcpy( ptrlast, «Jefferson» );


INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Thanks. We have received your request and will respond promptly.

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It’s Free!

*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

compiler error «Different levels of indirection»

compiler error «Different levels of indirection»

(OP)

12 Mar 02 12:23

Could somebody please explain what this message means?

I have looked at the microsoft site, but it has helped little.

James Goodman

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Join Tek-Tips® Today!

Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.

Here’s Why Members Love Tek-Tips Forums:

  • Tek-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More…

Register now while it’s still free!

Already a member? Close this window and log in.

Join Us             Close

  • Remove From My Forums
  • Question

  • hello ,
    i’m writing  a B+tree implementation in C . using visual studios 2008 
    i built 2 header files to help me with some  functionality, 
    one is called linked.h witch holds function and structs witch implement a stack using linked list ( for tree traversel  , the other is called nodewraper.h , it holds a struct for node ( of a B+tree ) and another struct called node_wraper witch encapsulates
    the node and the current visited pointer number (index)

    all the above is irrelevant , and is just written for thous people who just have to know what i’m trying to do .

    i believe in focusing  the problem :
    iv’e underlined the error below in the code , this is the header file nodewraper.h ,
    the error returns twice in make_leaf and make_node , i cant figure out its origin .
    iv’e tried replacing node* with void* to imply a general type but i got the same error as before only with void* instead of node*

    #include<linked.h>
    #include<stdlib.h>
    
    #define order 5
    
    typedef struct node 
    {
     void ** pointers;
     int * keys;
     struct node * parent;
     int is_leaf;
     int num_keys;
     struct node * next; 
    } node;
    
    typedef struct 
    {
    	node* _node ;
    	int visited ;
    }node_wraper;
    
    void Init(node** root)
    {	
      (*root) = make_leaf();  	
    	(*root)->parent = NULL;	
    	return root;
    }
    node* make_leaf() 
    { // here i get an error : : 'make_leaf' : 'node*()' 
     //differs in levels of indirection from 'int ()' 
      node* leaf = make_node();	
      leaf->is_leaf = 1;
      return leaf;
    } // end make_leaf
    
    
    node* make_node() 
    { // here i get an error : error C2040 : 'make_node' : 'node*()' 
     //differs in levels of indirection from 'int ()' 
     	
     node* new_node;
     new_node =(node*)malloc(sizeof(node));
     if (new_node == NULL) {
      perror("Node creation.");
      exit(EXIT_FAILURE);
     }
     new_node->keys =(int*) malloc( (order - 1) * sizeof(int) );
     if (new_node->keys == NULL) {
      perror("New node keys array.");
      exit(EXIT_FAILURE);
     }
     new_node->pointers =(node**)malloc( order * sizeof(node*) );
     if (new_node->pointers == NULL) {
      perror("New node pointers array.");
      exit(EXIT_FAILURE);
     }
     new_node->is_leaf = 0;
     new_node->num_keys = 0;
     new_node->parent = NULL;
     new_node->next = NULL;
     return new_node;
    } // end make node 
    

Answers

  • On 6/22/2011 8:17 PM, eranotz50 wrote:

    void Init(node** root)
    {       (*root) = make_leaf();

    You are calling a function without declaring it first. In C++, this is illegal. But the C compiler accepts it and synthesizes a declaration for you — like this:

    int make_leaf();

    node* make_leaf()
    { // here i get an error : : ‘make_leaf’ : ‘node*()’
      //differs in levels of indirection from ‘int ()’

    And here the compiler complains that the function signature differs from the one it synthesized earlier.

    Bottom line — declare names before using them.


    Igor Tandetnik

    • Marked as answer by

      Thursday, June 23, 2011 1:26 AM

View previous topic :: View next topic  
Author Message
septillion

Joined: 21 Jan 2010
Posts: 13

View user's profile
Send private message

Different levels of indirection
PostPosted: Wed Sep 28, 2016 4:50 am     Reply with quote

Hi all,

After some time not working with PICs I tried to make a new program for an older project. But I keep running into this error.

In my project I want to pass a struct to a function. No problem there but once I make an array of structs and try to loop over each I’m stuck with the error.

Of course my project is a bit bigger (but I wouldn’t call it big) but I made a small example which gives the same error.

Code:

#include <16F628A.h>

#fuses INTRC_IO,NOWDT,NOPROTECT,PUT, NOMCLR, BROWNOUT  //internal clock, no watchdog, no code protection, power up timer, Mater Clear pin used for I/O, brownout protection

#use delay(clock=4000000) //set clock speed

typedef struct{

  int one;

  int two;

} _myStruct;

_myStruct myStructs[2];

void setHundred(_myStruct &in){

  in.two = 100;

}

void main(){

  myStructs[0].one = 2; //normal struct set, no problem

 

  setHundred(myStructs[0]); //using the function on a array member, no error

 

 

  //but this gives me the «Different levels of indirection»-error

  for(byte i = 0; i < 2; i++){

    setHundred(myStructs[i]); //this line

  }

}

And to be complete, full error message:

Code:

Error[105]   structTest.c 26 : Different levels of indirection

      1 Errors,  0 Warnings.

Build Failed.

Is it really not possible to loop over array items and pass them by reference to a function Shocked That would really break all possibility of scaling a program Confused Or has anyone an alternative?

Timo

jeremiah

Joined: 20 Jul 2010
Posts: 1281

View user's profile
Send private message

PostPosted: Wed Sep 28, 2016 6:52 am     Reply with quote

Keep in mind that reference parameters are not a C construct but a C++ one and used as an extension to CCS C. They don’t necessarily follow the rules of C++ since they are merely an extension.

This issue is that CCS uses reference parameters to pass *known at compile time* addresses through a function (and as a side effect it normally inlines that function as well).

myStructs[i] cannot have a known compile time address since i is not a compile time constant and changes at runtime.

That’s why it thinks there are different levels of indirection (a bit of a loose definition IMO, but it is what it is).

To do what you want to do, you need to pass the parameter as a pointer:

Code:

void setHundred(_myStruct *in){

  in->two = 100;

}

and call it like:

Code:

setHundred(&myStructs[i]);

Ttelmah

Joined: 11 Mar 2010
Posts: 18356

View user's profile
Send private message

PostPosted: Wed Sep 28, 2016 7:00 am     Reply with quote

It’s perfectly possible.

You are having a problem because of C shortcuts, and getting misled about what they can do.

myStructs[n], is a structure of type _myStruct, not a pointer to such a structure. That is why you can access an element in such a reference directly. myStructs, is a shortcut to the address of the array.

This is only described in K&R, to work directly with the array name, not with a ‘sub element’ of the array. CCS happens to automatically treat a fixed index to such a sub element in the same way, but not with a variable, and it is honestly a little bit dangerous was to work.

So:

Code:

  for(byte i = 0; i < 2; i++){

    setHundred(&myStructs[i]); //gives the address of structure ‘i’ in the array

Honestly, I’d only use the array name «on it’s own» as the shortcut, and if wanting to pass the address of an element, always use the ‘&’. Safer, and avoids differences between C versions.

The other way is to use the offset in a different way:

Code:

  for(byte i = 0; i < 2; i++){

    setHundred(myStructs+i); //gives the address of structure ‘i’

This is because ‘myStructs’ is the address of the first element, and if you add to such a pointer, you automatically increment in ‘element sized’ lumps, so ‘myStructs_+i’, is defined as the address of element ‘i’ in the array.

The fact you are using reference parameters in the target function, does not really affect things. It still expects to receive an address, it is just that it then ‘works back’ and works on the source variable, not the copy in the function.

For a structure, why not just use the reference access mode (using -> instead of ‘.’ to access the sub variable)?. I see Temtronic has said this as well. It is a much safer way of working….

septillion

Joined: 21 Jan 2010
Posts: 13

View user's profile
Send private message

PostPosted: Wed Sep 28, 2016 8:21 am     Reply with quote

First of all, thanks guys!

I’m indeed more of a C++ guy Embarassed I started with PIC but moved to AVR (or ARM now) because of the open tool chains. But this is still an old project I want to revise which means, reprogramming the PIC.

But you say this can’t be done by reference in CCS C? I did it by reference instead of pointer because I think it just looks cleaner to call something like myFunction(instance) then to have to add the address operator.

In the past I have used this code (button debounce with passing by reference) multiple times without a problem but always on a single button. And I could make multiple structs insteads of an array of structs but that would make looping over them harder (aka, harder to scale).

But if by pointer will work fine I will just use that.

And about the operator, what is the difference between ‘.’ and ‘->’ as an operator?

Ttelmah

Joined: 11 Mar 2010
Posts: 18356

View user's profile
Send private message

PostPosted: Wed Sep 28, 2016 8:37 am     Reply with quote

Three different versions:

By pointer.

By reference pointer.

By reference.

By reference, is not a C ability. CCS offers it, but with limited abilities. Has to be directly ‘to’ a variable.

By pointer — standard.

By reference pointer, is for things like structures. On this you can pass a pointer ‘to’ a function, but then use it inside the function without having to de-reference it, to operate directly on the original variable. It is to do exactly what you are trying to do. So:

Code:

#include <16F628A.h>

#fuses INTRC_IO,NOWDT,NOPROTECT,PUT, NOMCLR, BROWNOUT  //internal clock, no watchdog, no code protection, power up timer, Mater Clear pin used for I/O, brownout protection

#use delay(clock=4000000) //set clock speed

typedef struct{

  int one;

  int two;

} _myStruct;

_myStruct myStructs[2];

void setHundred(_myStruct *in){

  in->two = 100; //note this change

}

void main(void)

{

  myStructs[0].one = 2; //

 

  setHundred(myStructs); //using the function on first array member

  //Or

  setHundred(&myStructs[1]); //second

  //Or

  setHundred(myStructs+2); //and third

 

  for(byte i = 0; i < 2; i++){

    setHundred(&myStructs[i]); //use second method for now

  }

}

jeremiah

Joined: 20 Jul 2010
Posts: 1281

View user's profile
Send private message

PostPosted: Wed Sep 28, 2016 9:00 am     Reply with quote

septillion wrote:

And about the operator, what is the difference between ‘.’ and ‘->’ as an operator?

‘.’ is element/member selector and is used directly on structs:

Code:

_myStruct struct1;

struct1.one = 1;

‘->’ is a dereference pointer and select element/membor. This is used with pointers to structs:

Code:

_myStruct * struct1_ptr;

struct1_ptr = &struct1;  //save the address of struct1 in the pointer

struct1_ptr->one = 1;   //does the same thing as struct1.one = 1;

alternate syntax to the ‘->’ is:

Code:

(*struct1_ptr).one = 1;

but I guess they decided that was too messy and added the arrow operator instead.

septillion

Joined: 21 Jan 2010
Posts: 13

View user's profile
Send private message

PostPosted: Wed Sep 28, 2016 10:24 am     Reply with quote

Thanks for explaining guys!

Alright, I tried to change my small library to use pass by pointers instead of pass by reference. So I change all the references to pointer (from &b to *b) and all the member operators to dereference member operators (brom b. to b->). And in my code I added the address of operator in front of struc variable names. And tada, it broke it Shocked

So my library to debounce buttons, and yes, it’s heavily inspired by Arduino Rolling Eyes

With pass by reference.

Code:

#define millis() get_ticks()

typedef struct{

  int   pin;

  long  lastMillis;

  int1  debouncedState;

  int1  unstableState;

  int1  changed;

} _button;

void buttonAttach(_button &b, int pin);

int1 buttonUpdate(_button &b);

int1 buttonRead(_button &b);

int1 buttonRose(_button &b);

int1 buttonFell(_button &b);

int1 buttonChanged(_button &b);

void buttonAttach(_button &b, int pin){

  b.pin = pin;

  if(input(b.pin)){

    b.debouncedState = 1;

    b.unstableState = 1;

  }

  else{

    b.debouncedState = 0;

    b.unstableState = 0;

  }

  b.changed = 0;

  b.lastMillis = millis();

}

 

 

int1 buttonUpdate(_button &b){

  // Read the state of the switch in a temporary variable

  int1 currentState = input(b.pin);

  b.changed = 0; //and clear changed

  // If the reading is different from last reading, reset the debounce counter

  if ( currentState != b.unstableState) {

    b.lastMillis = millis();

    b.unstableState = currentState; //flip unstable state

  }

  //Reading is the same, long enough?

  else if( millis() — b.lastMillis >= 10 ){

    // We have passed the threshold time, so the input is now stable

    // If it is different from last state, set the STATE_CHANGED flag

    if (b.debouncedState != currentState) {

      b.lastMillis = millis();

      b.debouncedState = currentState; //flip debounced state

      b.changed = 1; //state state changed

    }

  }

  return b.changed;

}

int1 buttonRead(_button &b){

  return b.debouncedState; //return debounced state

}

int1 buttonRose(_button &b){

  //debounced state high and state changed

  return (b.debouncedState && b.changed);

}

int1 buttonFell(_button &b){

  //debounced state low and state changed

  return !b.debouncedState && b.changed;

}

//Return true if state changed

int1 buttonChanged(_button &b){

  return b.changed;

}

Test code:

Code:

#include <16F648A.h>

#fuses INTRC_IO,NOWDT,NOPROTECT,PUT, NOMCLR, BROWNOUT  //internal clock, no watchdog, no code protection, power up timer, Mater Clear pin used for I/O, brownout protection

#use delay(clock=4000000) //set clock speed

//Setup timer for get_ticks() / millis()

#USE TIMER(TIMER=1, TICK=1ms, BITS=16, ISR)

#include <debounce.c>

#define millis()  get_ticks()

//const int8 BellButtonPins[] = {PIN_A2, PIN_A3};

const int8 ButtonPin        = PIN_A2;

const int8 OutputPin        = PIN_A0;

const int8 AnotherOutputPin = PIN_A1;

_button myButton;

void main(){

  enable_interrupts(GLOBAL);

 

  buttonAttach(myButton, ButtonPin);

 

  while(true){

    //output_bit(PIN_A0, input(PIN_A2));

    buttonUpdate(myButton);

   

    output_bit(OutputPin, !buttonRead(myButton));

   

    //calling it without debounce

    output_bit(AnotherOutputPin, !input(ButtonPin));

  }

}

Works like a charm, leds on both outputs turn on. One via debounce.

So after changing it:

library

Code:

#define millis() get_ticks()

typedef struct{

  int   pin;

  long  lastMillis;

  int1  debouncedState;

  int1  unstableState;

  int1  changed;

} _button;

void buttonAttach(_button *b, int pin);

int1 buttonUpdate(_button *b);

int1 buttonRead(_button *b);

int1 buttonRose(_button *b);

int1 buttonFell(_button *b);

int1 buttonChanged(_button *b);

void buttonAttach(_button *b, int pin){

  b->pin = pin;

  if(input(b->pin)){

    b->debouncedState = 1;

    b->unstableState = 1;

  }

  else{

    b->debouncedState = 0;

    b->unstableState = 0;

  }

  b->changed = 0;

  b->lastMillis = millis();

}

 

 

int1 buttonUpdate(_button *b){

  // Read the state of the switch in a temporary variable

  int1 currentState = input(b->pin);

  b->changed = 0; //and clear changed

  // If the reading is different from last reading, reset the debounce counter

  if ( currentState != b->unstableState) {

    b->lastMillis = millis();

    b->unstableState = currentState; //flip unstable state

  }

  //Reading is the same, long enough?

  else if( millis() — b->lastMillis >= 10 ){

    // We have passed the threshold time, so the input is now stable

    // If it is different from last state, set the STATE_CHANGED flag

    if (b->debouncedState != currentState) {

      b->lastMillis = millis();

      b->debouncedState = currentState; //flip debounced state

      b->changed = 1; //state state changed

    }

  }

  return b->changed;

}

int1 buttonRead(_button *b){

  return b->debouncedState; //return debounced state

}

int1 buttonRose(_button *b){

  //debounced state high and state changed

  return (b->debouncedState && b->changed);

}

int1 buttonFell(_button *b){

  //debounced state low and state changed

  return !b->debouncedState && b->changed;

}

//Return true if state changed

int1 buttonChanged(_button *b){

  return b->changed;

}

Test code:

Code:

#include <16F648A.h>

#fuses INTRC_IO,NOWDT,NOPROTECT,PUT, NOMCLR, BROWNOUT  //internal clock, no watchdog, no code protection, power up timer, Mater Clear pin used for I/O, brownout protection

#use delay(clock=4000000) //set clock speed

//Setup timer for get_ticks() / millis()

#USE TIMER(TIMER=1, TICK=1ms, BITS=16, ISR)

#include <debounce.c>

#define millis()  get_ticks()

//const int8 BellButtonPins[] = {PIN_A2, PIN_A3};

const int8 ButtonPin        = PIN_A2;

const int8 OutputPin        = PIN_A0;

const int8 AnotherOutputPin = PIN_A1;

_button myButton;

void main(){

  enable_interrupts(GLOBAL);

 

  buttonAttach(&myButton, ButtonPin);

 

  while(true){

    //output_bit(PIN_A0, input(PIN_A2));

    buttonUpdate(&myButton);

   

    output_bit(OutputPin, !buttonRead(&myButton));

   

    //calling it without debounce

    output_bit(AnotherOutputPin, !input(ButtonPin));

  }

}

I would think it should still do the same but only the direct controlled output turns on :/ What am I missing?

Ttelmah

Joined: 11 Mar 2010
Posts: 18356

View user's profile
Send private message

PostPosted: Wed Sep 28, 2016 12:37 pm     Reply with quote

I didn’t look very far, but saw one glaring thing straight away. A pin number in a PIC, is an int16, not an int8. Remember ‘int’ in CCS is an int8. This will stop it working.
septillion

Joined: 21 Jan 2010
Posts: 13

View user's profile
Send private message

PostPosted: Wed Sep 28, 2016 12:49 pm     Reply with quote

Why is it a int16? It’s just defined as a macro. And on a PIC16F648A/628A it’s a number between 40 and 55. This might be different for other PICs but at least for the 16F648A I don’t see a problem. We can assign that to an int8 just fine.

And just to check I’m not to stubborn I changed the variable for the pin in the struct, attach-function and in the test code to int16 but that didn’t change a thing.

Ttelmah

Joined: 11 Mar 2010
Posts: 18356

View user's profile
Send private message

PostPosted: Wed Sep 28, 2016 1:18 pm     Reply with quote

Fair enough. I haven’t used a chip where it is an int8 for ages.

It’s actually the register number*8, plus the bit number.

It has to be an int16, if any pin on the chip requires an int16.

That does look as if it should work.

Why do you waste storage declaring the pin numbers?. Just use #defines for these.

septillion

Joined: 21 Jan 2010
Posts: 13

View user's profile
Send private message

PostPosted: Wed Sep 28, 2016 1:33 pm     Reply with quote

Like I said, old project, good old 16F628A (/648A) Very Happy

And yeah, I thought it would be something like that. Didn’t dive into it Smile So yeah, for compatibility it should be int16 but for the 16F648A int8 isn’t the problem.

And I’m «wasting memory» because this makes it easy to put pin numbers into an array and just loop over them. Great for scaling things.

But because they are const they should not waste memory because they are located in ROM. At least, that seems to be the default if I understand the help of #DEVICE correctly…

And last but not least, the passed by reference version works fine, the passed by pointer does not Crying or Very sad

Ttelmah

Joined: 11 Mar 2010
Posts: 18356

View user's profile
Send private message

PostPosted: Wed Sep 28, 2016 3:05 pm     Reply with quote

Making them into const, wastes a surprising amount of memory…..

Problem is there has to be code to read them. If you use a #define, the number is written directly inside the code at compile time. A variable, still has to be read.

Critical question now comes. What compiler version number are you using?.

Problems with things like pointers (and references etc..), are typical for some of the older compiler versions. What version are you on?.

septillion

Joined: 21 Jan 2010
Posts: 13

View user's profile
Send private message

PostPosted: Wed Sep 28, 2016 4:08 pm     Reply with quote

Mm, true, but the fact it’s scaleable is worth it Smile

I’m using 5.008, on old Uni license…. It’s a bug there? :/

jeremiah

Joined: 20 Jul 2010
Posts: 1281

View user's profile
Send private message

PostPosted: Thu Sep 29, 2016 6:33 am     Reply with quote

Can’t tell if it is a bug or not, but it appears to be with your use of int1’s. If I change all the int1 variables in the struct and in buttonUpdate to unsigned int8’s I get it to work.

I also changed lastMillis to be unsigned (it is an unsigned value, not a signed value, so the variable should match).

Code:

#define millis() get_ticks()

typedef struct{

  int16   pin;

  unsigned int16  lastMillis;

  unsigned int8  debouncedState;

  unsigned int8  unstableState;

  unsigned int8  changed;

} _button;

void buttonAttach(_button *b, int16 pin);

int1 buttonUpdate(_button *b);

int1 buttonRead(_button *b);

int1 buttonRose(_button *b);

int1 buttonFell(_button *b);

int1 buttonChanged(_button *b);

void buttonAttach(_button *b, int16 pin){

  b->pin = pin;

  if(input(b->pin)){

    b->debouncedState = 1;

    b->unstableState = 1;

  }

  else{

    b->debouncedState = 0;

    b->unstableState = 0;

  }

  b->changed = 0;

  b->lastMillis = millis();

}

 

 

int1 buttonUpdate(_button *b){

  // Read the state of the switch in a temporary variable

  unsigned int8 currentState = input(b->pin);

 

  b->changed = 0; //and clear changed

  // If the reading is different from last reading, reset the debounce counter

  if ( currentState != b->unstableState) {

    b->lastMillis = millis();

    b->unstableState = currentState; //flip unstable state

  }

  //Reading is the same, long enough?

  else if( millis() — b->lastMillis >= 10 ){

    // We have passed the threshold time, so the input is now stable

    // If it is different from last state, set the STATE_CHANGED flag

    if (b->debouncedState != currentState) {

      b->lastMillis = millis();

      b->debouncedState = currentState; //flip debounced state

      b->changed = 1; //state state changed

    }

  }

  return b->changed;

}

int1 buttonRead(_button *b){

  return b->debouncedState; //return debounced state

}

int1 buttonRose(_button *b){

  //debounced state high and state changed

  return (b->debouncedState && b->changed);

}

int1 buttonFell(_button *b){

  //debounced state low and state changed

  return !b->debouncedState && b->changed;

}

//Return true if state changed

int1 buttonChanged(_button *b){

  return b->changed;

}

I am compiling with 5.061 and using a PIC24FJ64GA004 since I don’t have any 8 bit chips lying around.

You might send an email to CCS support with both files and see what they say about it.

septillion

Joined: 21 Jan 2010
Posts: 13

View user's profile
Send private message

PostPosted: Fri Sep 30, 2016 7:29 am     Reply with quote

Thanks for testing! I will give it a try once I’m back home. Did not bring my PicKit 2 with me.

I first wanted to say a int1 is just defined as a int8 but then I saw that’s only the case if the compiler isn’t PCM. So int1 is a build in type.

I did not specify the unsigned type because the CCS Help says «Unsigned: Data is always positive. This is the default data type if not specified.». But I agree it’s nicer to specify it specifically.

And because how a pin number is build up, isn’t that a unsigned as well? (Not that it matters because of the unsigned as default type.)

I will also send an email. Because it’s indeed a bit strange it does work with a int8. For now I’ll just use a int8 to do it, project is small and I can handle the extra memory. But I think I’ll change the library to use one byte for all the states (different bits in the same byte) to same some.

But thanks again or helping!

Display posts from previous:   

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group

I am posting two threads because I have two different problems, but both have the same background information.

Common Background Information:

I am trying to rebuild code for a working, commercially sold application with only partial build instructions. The previous maintainer of the code (a mixture of C and C++) is no longer with the company, but when he built the code he used MSVC++, and though I am not certain of the version he was using, I think it was either 4.0 or 6.0. I have only a little experience building with this environment (I am otherwise a seasoned developer) so I need help getting past a couple of issues that I have encountered. Computers (and backups of those computers) previously used for running this build are now completely unavailable.

I have set up the build on my system using MSVC++ 6.0. The source repository contained a workspace (.dsw) file that I am using for all of the projects. I do not have specific instructions for this product on how to adjust the references to libraries, includes, etc. for a particular machine, but I am using instructions for this from a similar (in terms of languages and tools used) product that was written around the same time. I have gotten 43 of 53 classes (projects) to build, but am getting primarily two errors with the remaining 10 clases (projects).

Because I know this code base was building properly (for someone else who is no longer available on a machine that is no longer available), I would strongly prefer adjustments to the build environment over code modification to get it to work, so please focus your assistance/suggestions in this area.

Thanks !

Problem #1: Error C2040: … differs in levels of indirection from …

Here are the exact error messages I am receiving:

Fxactn.cpp
develop3rdPartyxvtdsp45w32_x86includexvt_type.h(54) : error C2040: ‘LONG_PTR’ : ‘long *’ differs in levels of indirection from ‘long’
develop3rdPartyxvtdsp45w32_x86includexvt_type.h(55) : error C2040: ‘ULONG_PTR’ : ‘unsigned long *’ differs in levels of indirection from ‘unsigned long’
Fxapifun.cpp
C:PROGRAM FILESMICROSOFT SDKINCLUDEbasetsd.h(92) : error C2040: ‘LONG_PTR’ : ‘long’ differs in levels of indirection from ‘long *’
C:PROGRAM FILESMICROSOFT SDKINCLUDEbasetsd.h(93) : error C2040: ‘ULONG_PTR’ : ‘unsigned long’ differs in levels of indirection from ‘unsigned long *’
Guicinit.cpp
develop3rdPartyxvtdsp45w32_x86includexvt_type.h(54) : error C2040: ‘LONG_PTR’ : ‘long *’ differs in levels of indirection from ‘long’
develop3rdPartyxvtdsp45w32_x86includexvt_type.h(55) : error C2040: ‘ULONG_PTR’ : ‘unsigned long *’ differs in levels of indirection from ‘unsigned long’

The first two errors and the last two errors come from the same include file. I put the errors twice simply to emphasize that I am receiving these errors on multiple source files. The middle two errors are only occurring once.

Here are lines 41 through 58 of xvt_type.h (apparently a third party include file):

typedef unsigned short T_LNUM;
typedef unsigned short T_PNUM;
typedef unsigned long  XVT_COLOR_TYPE; /* Color Component Type (XVT_COLOR_* */

/* The following legacy "data types" are being phased out, as they cause    */
/* problems with constness: "const int *x" is NOT same as "const INT_PTR x" */
//typedef int           *INT_PTR;
typedef BOOLEAN       *BOOLEAN_PTR;
typedef char           XVT_BYTE;    /* raw data */
typedef unsigned char  XVT_UBYTE;   /* raw data */
typedef XVT_BYTE      *DATA_PTR;    /* ptr to arbitrary data - backwards compat. */
typedef XVT_UBYTE     *UDATA_PTR;   /* unsigned ptr to arbitrary data */
typedef XVT_UBYTE      DATA_BYTE;   /* for raw data */
typedef long          *LONG_PTR;          [B]/* THIS IS LINE 54 */[/B]
typedef unsigned long *ULONG_PTR;        [B]/* THIS IS LINE 55 */[/B]

/* define a point to function which will be used in xvt_win_enum_wins etc. */
typedef XVT_CALLCONV_TYPEDEF( BOOLEAN, XVT_ENUM_CHILDREN, (WINDOW child, long data));

Here are the first 98 lines of the BaseTsd.h file:

/*++

Copyright (c) Microsoft Corporation.  All rights reserved.

Module Name:

    basetsd.h

Abstract:

    Type definitions for the basic sized types.

Author:

Revision History:

--*/

#ifndef _BASETSD_H_
#define _BASETSD_H_

#if _MSC_VER > 1000
#pragma once
#endif

#ifdef __cplusplus
extern "C" {
#endif

typedef signed char         INT8, *PINT8;
typedef signed short        INT16, *PINT16;
typedef signed int          INT32, *PINT32;
typedef signed __int64      INT64, *PINT64;
typedef unsigned char       UINT8, *PUINT8;
typedef unsigned short      UINT16, *PUINT16;
typedef unsigned int        UINT32, *PUINT32;
typedef unsigned __int64    UINT64, *PUINT64;

//
// The following types are guaranteed to be signed and 32 bits wide.
//

typedef signed int LONG32, *PLONG32;

//
// The following types are guaranteed to be unsigned and 32 bits wide.
//

typedef unsigned int ULONG32, *PULONG32;
typedef unsigned int DWORD32, *PDWORD32;

#if !defined(_W64)
#if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300
#define _W64 __w64
#else
#define _W64
#endif
#endif

//
// The INT_PTR is guaranteed to be the same size as a pointer.  Its
// size with change with pointer size (32/64).  It should be used
// anywhere that a pointer is cast to an integer type. UINT_PTR is
// the unsigned variation.
//
// __int3264 is intrinsic to 64b MIDL but not to old MIDL or to C compiler.
//
#if ( 501 < __midl )

    typedef [public] __int3264 INT_PTR, *PINT_PTR;
    typedef [public] unsigned __int3264 UINT_PTR, *PUINT_PTR;

    typedef [public] __int3264 LONG_PTR, *PLONG_PTR;
    typedef [public] unsigned __int3264 ULONG_PTR, *PULONG_PTR;

#else  // midl64
// old midl and C++ compiler

#if defined(_WIN64)
    typedef __int64 INT_PTR, *PINT_PTR;
    typedef unsigned __int64 UINT_PTR, *PUINT_PTR;

    typedef __int64 LONG_PTR, *PLONG_PTR;
    typedef unsigned __int64 ULONG_PTR, *PULONG_PTR;

    #define __int3264   __int64

#else
    typedef _W64 int INT_PTR, *PINT_PTR;
    typedef _W64 unsigned int UINT_PTR, *PUINT_PTR;

    typedef _W64 long LONG_PTR, *PLONG_PTR;
    typedef _W64 unsigned long ULONG_PTR, *PULONG_PTR;

    #define __int3264   __int32

#endif
#endif // midl64

My thoughts so far are as follows:

  1. One possibility is that the previous builder of this code precompiled these (and probably all 3rd party and MS) headers separately using a different environment or different settings prior to the build, and he had the pre-compiled headers available when he ran the main build, so he would not have gotten these errors.
  2. Another possibility is that the previous builder was using different settings for the compile than I am using — perhaps a older version compatability flag or something like that. However, if this was on the main build (as opposed to a separate run to precompile header files) I would expect that setting to be in the saved workspace (.dsw) file.
  3. The only other possibility that I have been able to come up with is that the previous builder was using or pointing to a later version of these header files than I am. I will look into this possibility, but I wanted to go ahead and post to get the ball rolling first, in case someone else had other helpful ideas.

Any thoughts or suggestions from an experienced MSVC++ user would be greatly appreciated.

Помогите пожалуйста разобраться с ошибками в коде

вот код:

C++
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream.h>
#include <string.h>
int main ()
{
struct strc{
int a[100];//номер
char b[100]; // тип автобуса
char c[100]; // пункт назначения
int  d[100]; // время отправления
int  D[100];
int  e[100];// время прибытия
int  E[100];
}bus[100];
int f,i,j,h,m;
cout << "vvedite kol-vo reisov"<<endl;
cin >> f;
for (i=0; i < f; i++)
{
    cout << "vvedite tip avtobusa"<<endl;
    cin >> bus[i].b;
cout << "vvedite punkt naznacheniya"<<endl;
cin >> bus[i].c;
cout << "vvedite vremya otpravleniya(hours(Enter)minutes)"<<endl;
cin >> bus[i].d;
cin >> bus[i].D;
cout << "vvedite vremya pribitiya(hours(Enter)minutes)"<<endl;
cin >> bus[i].e;
cin >> bus[i].E;
}
cout << "vvedite interesyUshee vas vremya pribitiya(hours(Enter)minutes)"<<endl;
cin >> h;
cin >> m;
for (j=0; j < f; j++)
{ 
    if(h > bus[j].e)
    {       
        if(m > bus[j].E)
        {
            cout << bus[j].a << " " << bus[j].b << " " << bus[j].c << " " << bus[j].d << " " << bus[j].D << " " << bus[j].e << " " << bus[j].E;
        }
    }
}
return 0;
}

При компиляции компилятор выдаёт такое:

» D:111111.cpp(24) : error C2679: binary ‘>>’ : no operator defined which takes a right-hand operand of type ‘int [100]’ (or there is no acceptable conversion)
D:111111.cpp(25) : error C2679: binary ‘>>’ : no operator defined which takes a right-hand operand of type ‘int [100]’ (or there is no acceptable conversion)
D:111111.cpp(27) : error C2679: binary ‘>>’ : no operator defined which takes a right-hand operand of type ‘int [100]’ (or there is no acceptable conversion)
D:111111.cpp(28) : error C2679: binary ‘>>’ : no operator defined which takes a right-hand operand of type ‘int [100]’ (or there is no acceptable conversion)
D:111111.cpp(35) : error C2446: ‘>’ : no conversion from ‘int *’ to ‘int’
This conversion requires a reinterpret_cast, a C-style cast or function-style cast
D:111111.cpp(35) : error C2040: ‘>’ : ‘int’ differs in levels of indirection from ‘int [100]’
D:111111.cpp(37) : error C2446: ‘>’ : no conversion from ‘int *’ to ‘int’
This conversion requires a reinterpret_cast, a C-style cast or function-style cast
D:111111.cpp(37) : error C2040: ‘>’ : ‘int’ differs in levels of indirection from ‘int [100]’ «

если понадобится — это решение вот этой задачи задачи:

«В справочной автовокзала хранится расписание движения автобусов.
Для каждого рейса указаны его номер, тип автобуса, пункт назначения, время
отправления и прибытия. Вывести информацию о рейсах, которыми можно
воспользоваться для прибытия в пункт назначения раньше заданного времени.»

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

Я получаю несколько ошибок компилятора, которые происходят из моего Copy-Constructor. Я понимаю, что первая ошибка происходит из-за несовместимых типов операндов, я просто не уверен в лучшем способе написания этого кода. И вторая ошибка, в которой я совсем не уверен. Почему бы не '=' быть в состоянии преобразовать из Узла * в Узел *?

Любая помощь или направление будут оценены.

Спасибо!

// Copy-Constructor
List::List(const List& theList)
{
Node* tempPtr = new Node;
tempPtr = theList.first;

//error C2040: 'tempPtr' : 'List' differs in levels of indirection from 'Node *'
List(tempPtr);

while (tempPtr != NULL)
{
Node* copyNode = new Node;

//error C2440: '=' :cannot convert from 'Node *' to 'Node *'
copyNode = tempPtr;

tempPtr = tempPtr->getNext();
nodeListTotal++;
}
}

Ниже мой конструктор и деструктор.

List::List():first(0), last(0), nodeListTotal(0)
{
}

// Destructor
List::~List()
{
Node* currentNode = first;

while(currentNode != NULL)
{
Node* temp = currentNode;
currentNode = currentNode->getNext();
delete temp;
}
}

0

Решение

Здесь есть несколько проблем. Во-первых, C2040 и C2440, где типы одного типа. На основании того, что я нашел в этой дискуссии, круглые скобки разрешены в объявлении, поэтому утверждение:

List(tempPtr);

по-видимому, эквивалентно:

List tempPtr;

Следовательно, ошибка — это очень запутанный способ сказать, что вы объявили переменную tempPtrи вы дали ему другой тип. Но учтите, что если вы написали List*(tempPtr) было бы сказать redefinition: different basic typesтак что это также, похоже, связано с тем, что List не столько указатель, сколько Node* (вот откуда берется «уровень косвенности»). C2440 происходит из-за повторного объявления. Вы можете подтвердить это, комментируя List(tempPtr); и увидев, что код скомпилируется. Однако тот факт, что он будет компилироваться, вовсе не означает, что это правильно.

Проблема № 2 в том, что вы не показываете здесь конструктор, принимающий Node*и даже если бы у вас был один, это не будет правильным способом назвать это. Я не совсем уверен, что вы пытаетесь сделать с этим.

Проблема № 3 в том, что вы протекаете Node объекты как сумасшедшие. Когда вы выполняете строки:

Node* tempPtr = new Node;
tempPtr = theList.first;

а также

Node* copyNode = new Node;
copyNode = tempPtr;

вы распределяете Node объекты, а затем выбрасывая указатели на них. Если вы пытаетесь скопировать Node объекты, это не способ сделать это. Вам тоже нужен конструктор копирования.

Это не все, что входит в правильный конструктор копирования для вашего List класс, но он покрывает некоторые из самых больших проблем с кодом, который вы разместили, и, особенно, кажется, именно поэтому вы получаете эти две ошибки.

0

Другие решения

Ситуация выглядит как сочетание какого-то недопонимания с вашей стороны и ошибки компилятора.

Формально заявление

 List(tempPtr);

должен интерпретироваться компилятором как объявление

 List tempPtr;

В спецификации языка 6.8 (C ++ 03) четко указано, что неоднозначность между объявлением и функциональным выражением приведена в пользу или объявлении. Это означает, что у вас есть недопустимая переопределение переменной tempPtr, Вы уже заявили tempPtr раньше с другим типом.

Тем не менее, сообщение об ошибке, выдаваемое компилятором, похоже, предполагает, что компилятор интерпретировал его как функциональное выражение приведения (вместо объявления). Это выражение пытается создать безымянный временный объект типа List из указателя tempPtr типа Node *, Этот временный объект (если он успешно создан) будет немедленно уничтожен. Тем не менее, класс List не имеет конструктора, который может построить его из Node * указатель. Это то, что говорит вам компилятор. Твой класс List имеет только один однопараметрический конструктор, который принимает const List &в то время как вы поставили Node *, Компилятор говорит вам, что не может конвертировать Node * в List чтобы вызвать этот конструктор.

Тем не менее, независимо от того, как кто-то интерпретирует это утверждение (выражение или объявление), это не имеет смысла в контексте вашего кода. Это сломано в любом случае. Итак, в основном, вопрос в том, что на Земле вы пытаетесь делать с этим List(tempPtr); линия? Каково было ваше намерение?

Вторая ошибка, вероятно, вызвана первой.

0

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Different client and server versions 1c ошибка
  • Diff lock ошибка на квадроцикле