關於C語言指標賦值的問題詳解

來源:互聯網
上載者:User

一個代碼:

複製代碼 代碼如下:#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: 警告: 賦值時將指標賦給整數,未作類型轉換
test.c:22: 警告: 賦值時將指標賦給整數,未作類型轉換
test.c:23: 警告: 賦值時將指標賦給整數,未作類型轉換
test.c:24: 警告: 賦值時將指標賦給整數,未作類型轉換
test.c:25: 警告: 賦值時將指標賦給整數,未作類型轉換
test.c:29: 警告: 傳遞參數 1 (屬於 ‘display')時將整數賦給指標,未作類型轉換

其中21-25就是
set[0] = h;
set[1] = e;
set[2] = l;
set[3] = l;
set[4] = o;
29是
display(set[i])

雖然只是警報,並且在linux下面也可以啟動並執行很好.但是既然警告了.還是值得討論下.

待續~
關注中...

如果有哪位知道.可否回複告訴我.謝謝~

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

關於這個問題,我問了寢室的小丁.經過他的修改.程式已經不警示告了.

複製代碼 代碼如下:#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;
}
}

在字模數組的首地址賦值方面用了強制轉換為int.在函數調用方面.因為子函數中要求到輸入為指標,所以在前面的調用時候,不能單純的寫set[i].而是傳指標過去.(uchar *)的強制類型轉換是為了配合(uchar *p).
-------------------------------------------
應該注意的2點是:
1.給指標只能傳地址,不能傳值.否則要做強制類型轉換.
2.在做類型轉換和賦值時候,應該注意賦值的類型匹配.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.