曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 4133|回复: 1
打印 上一主题 下一主题

指针

[复制链接]

4917

主题

5879

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34382
跳转到指定楼层
楼主
发表于 2009-4-22 22:05:49 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
函数的返回类型
#include <stdio.h>

char message[100] = {"hello world"};

void *test(void)
{
        char *p = message;
        printf("%s\n",p);
        return p;
}

int main()
{
        char *charp;

        printf("-----subfunction area--------\n");
        test();

        printf("------main function area-------");
        charp = test();

        printf("%s\n", charp);
        return 0;
说明
test() 中声明的返回值是 void * 类型, test() 中的 p 为 char * 类型;但由于 void * 是个万能指针,所以,函数返回时,仍然被转换为 char * 类型,故编译时不会发出警告信息。

4917

主题

5879

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34382
沙发
 楼主| 发表于 2009-7-10 15:09:39 | 只看该作者

const 字符串 与 const 指针

有错误的代码
#include <stdio.h>

int main()
{
    const char *arg = "hell world!";
    char const *p = "new world!";
    char *const q = "old world!";
    printf("%c\\n", *arg);
    arg++;
    printf("%c\\n", *arg);
    *arg = 'X';
    printf("%c\\n", *arg);
   
    printf("%c\\n", *p);
    p++;
    printf("%c\\n", *p);

    printf("%c\\n", *q);
    q++;
    printf("%c\\n", *q);


    return 0;
}
编译时提示
beyes@linux-beyes:~/C> gcc -g const.c -o const.exe
const.c: In function ‘main’:
const.c:11: error: assignment of read-only location ‘*arg’
const.c:19: error: increment of read-only variable ‘q’
说明
char const *p = "new world!";
char *const q = "old world!";
上面的两个定义是一样的。

编译出错中的第一行,是因为 const 字符串为常数字符串,字符串中的元素不能更改,像上面想把 e 字符改成 X 就不行,会报错。然而指向字符串的指针(arg)可以移动。

char *const q = "old world!"; 这种定义,是定义了一个 const 指针,它本身所指向的非 const 字符串中的元素可以改变,但自己自身不能移动,可以将其复制给另外一个非 const 的指针来进行字符串的修改。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2024-5-13 21:09 , Processed in 0.079462 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表