On C language pointer assignment problem in detail

  • 2020-04-01 23:37:14
  • OfStack

A code:


#include<stdio.h>
#include<stdlib.h>
#define uchar unsigned char
#define uint unsigned int
void display(uchar *p);
char h[4] = {'A','B','C','0'};
char e[4] = {'E','F','L','0'};
char l[4] = {'M','N','O','0'};
char o[4] = {'X','Y','Z','0'};
int main(void)
{
    int i;
    char c;
    uint set[5];
    set[0] = h;
    set[1] = e;
    set[2] = l;
    set[3] = l;
    set[4] = o;
       while(1){
           for (i = 0; i < 5; ++i){
                display(set[i]);
                printf("n");
                sleep(1);
          }
       }
}
void display(uchar *p)
{
   while(*p != '0'){
    printf("%c", *p);
    printf("%c", *(p+1));
    ++p;
    }
}

The warning is as follows:

Test.c :21: warning: assigns a pointer to an integer when assigning a value, not cast
Test.c :22: warning: assigns a pointer to an integer when assigning a value, not cast
Test.c :23: warning: assigns a pointer to an integer, not cast
Test.c :24: warning: assigns a pointer to an integer, not cast
Test.c :25: warning: assigns a pointer to an integer at assignment, not cast
Test.c :29: warning: assign an integer to the pointer when passing parameter 1 (belonging to 'display'), no casting

Where 21 minus 25 is equal to
The set [0] = h;
The set [1] = e;
The set [2] = l;
The set [3] = l;
The set [4] = o;
29 is
The display (set [I])

It's just an alert, and it works fine under Linux. But now that it's an alert, it's worth discussing.

To be continued ~
Pay attention to in...

If anyone knows, please reply and let me know. Thanks

------------------------------------------------------------

On this question, I asked the dormitory of xiaoding. After his modification. The procedure has not reported the warning.


#include<stdio.h>
#include<stdlib.h>
#define uchar unsigned char
#define uint unsigned int
void display(uchar *p);
char h[4] = {'A','B','C','0'};
char e[4] = {'E','F','L','0'};
char l[4] = {'M','N','O','0'};
char o[4] = {'X','Y','Z','0'};
int main(void)
{
    int i;
    char c;
    int set[5];
    set[0] =(int) h;
    set[1] =(int) e;
    set[2] =(int) l;
    set[3] =(int) l;
    set[4] =(int) o;
       while(1){
           for (i = 0; i < 5; ++i){
                display((uchar *)set[i]);
                printf("n");
                sleep(1);
          }
       }
}
void display(uchar *p)
{
   while(*p != '0'){
    printf("%c", *p);
    printf("%c", *(p+1));
    ++p;
    }
}

Cast int in the first address of the array. In the function call. Because the subfunction requires the input as a pointer, so in the previous call, you cannot simply write set[I].
-------------------------------------------
Two things to note:
1. Pointer can only be passed address, not value. Otherwise, to do a cast.
2. When doing type conversions and assignments, you should pay attention to the type matching of assignments.


Related articles: