曲径通幽论坛

标题: 指针 [打印本页]

作者: beyes    时间: 2009-4-22 22:05
标题: 指针
函数的返回类型
#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 * 类型,故编译时不会发出警告信息。
作者: beyes    时间: 2009-7-10 15:09
标题: 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 的指针来进行字符串的修改。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2