關(guān)于C語言指針賦值的問題詳解
一個代碼:
#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;
}
}
警報如下:
test.c:21: 警告: 賦值時將指針賦給整數(shù),未作類型轉(zhuǎn)換
test.c:22: 警告: 賦值時將指針賦給整數(shù),未作類型轉(zhuǎn)換
test.c:23: 警告: 賦值時將指針賦給整數(shù),未作類型轉(zhuǎn)換
test.c:24: 警告: 賦值時將指針賦給整數(shù),未作類型轉(zhuǎn)換
test.c:25: 警告: 賦值時將指針賦給整數(shù),未作類型轉(zhuǎn)換
test.c:29: 警告: 傳遞參數(shù) 1 (屬于 ‘display')時將整數(shù)賦給指針,未作類型轉(zhuǎn)換
其中21-25就是
set[0] = h;
set[1] = e;
set[2] = l;
set[3] = l;
set[4] = o;
29是
display(set[i])
雖然只是警報,并且在linux下面也可以運行的很好.但是既然警告了.還是值得討論下.
待續(xù)~
關(guān)注中...
如果有哪位知道.可否回復(fù)告訴我.謝謝~
------------------------------------------------------------
關(guān)于這個問題,我問了寢室的小丁.經(jīng)過他的修改.程序已經(jīng)不報警告了.
#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;
}
}
在字模數(shù)組的首地址賦值方面用了強制轉(zhuǎn)換為int.在函數(shù)調(diào)用方面.因為子函數(shù)中要求到輸入為指針,所以在前面的調(diào)用時候,不能單純的寫set[i].而是傳指針過去.(uchar *)的強制類型轉(zhuǎn)換是為了配合(uchar *p).
-------------------------------------------
應(yīng)該注意的2點是:
1.給指針只能傳地址,不能傳值.否則要做強制類型轉(zhuǎn)換.
2.在做類型轉(zhuǎn)換和賦值時候,應(yīng)該注意賦值的類型匹配.
相關(guān)文章
簡要說明C語言中指針函數(shù)與函數(shù)指針的區(qū)別
這篇文章主要介紹了C語言中指針函數(shù)與函數(shù)指針的區(qū)別,指針函數(shù)和函數(shù)指針是C語言入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2016-04-04