对指针**p的分析研究

最近看到ChinaUnix有人问一个二维数组的问题,提问者写成这个样子:
#include<stdio.h>
#include<string.h>
void f(char (*c)[2][4]){
  printf("c[0]=%s,c[1]=%s\n",*(c[0]),*(c[1]));
  strcpy(*(c[0]),"123");
}
int main(){
  char buf[2][4]={"xyz","abc"};
  printf("size=%d\n",sizeof(buf));
  printf("buf[0]=%s,buf[1]=%s\n",buf[0],buf[1]);
  f(&buf);
  printf("after f()\n");
  printf("buf[0]=%s,buf[1]=%s\n",buf[0],buf[1]);
  return 0;
}
上面这个式子是不正确的,很容易误解,*(c[0]) ?= (*c)[0],实际上, *c就是buf的地址,不能分开的:
#include<stdio.h>
#include<string.h>
void f(char (*c)[2][4]){
    printf("c[0]=%s,c[1]=%s\n",(*c)[0],(*c)[1]);
    strcpy((*c)[0],"123");
}
int main(){
    char buf[2][4]={"xyz","abc"};
    printf("size=%d\n",sizeof(buf));
    printf("buf[0]=%s,buf[1]=%s\n",buf[0],buf[1]);
    f(&buf);
    printf("after f()\n");
    printf("buf[0]=%s,buf[1]=%s\n",buf[0],buf[1]);
    return 0;
}
另外写法可以如下:
#include<stdio.h>
#include<string.h>
void f(char (*c)[2][4]){
  printf("c[0]=%s,c[1]=%s\n",*(c[0]),*(c[0])+4);
  strcpy(*(c[0]),"123");
}
int main(){
  char buf[2][4]={"xyz","abc"};
  printf("size=%d\n",sizeof(buf));
  printf("buf[0]=%s,buf[1]=%s\n",buf[0],buf[1]);
  f(&buf);
  printf("after f()\n");
  printf("buf[0]=%s,buf[1]=%s\n",buf[0],buf[1]);
  return 0;
}
如果不传递二维数组,以*p呢?
#include<stdio.h>
#include<string.h>
void f(char *c){
    printf("c[0]=%.*s,c[1]=%.*s\n", 3, c, 3, c + 4);
    memcpy(c + 4, "123", 4);
}
int main(){
    char buf[2][4]={"xyz","abc"};
    printf("size=%d\n",sizeof(buf));
    printf("buf[0]=%s,buf[1]=%s\n",buf[0],buf[1]);
    char *p = (char *)buf;
    f(p);
    printf("after f()\n");
    printf("buf[0]=%s,buf[1]=%s\n",buf[0],buf[1]);
    return 0;
}
换种方式,以**p呢?
#include<stdio.h>
#include<string.h>
void f(char **c){
    ...
}
int main(){
    char buf[2][4]={"xyz","abc"};
    printf("size=%d\n",sizeof(buf));
    printf("buf[0]=%s,buf[1]=%s\n",buf[0],buf[1]);
    char **p = (char **)&buf;
    f(p);
    printf("after f()\n");
    printf("buf[0]=%s,buf[1]=%s\n",buf[0],buf[1]);
    return 0;
}
上面这个式子也是不正确的,注意的是,buf的地址是一个常量(静态分配),对常量的指针的指针,是不能直接访问的,可以采用:
char *p = (char *)&buf;
char **pp = &p;
f(pp);
另外,可以对变量的指针的指针进行直接访问,不过这里的变量就需要动态申请分配内存了(malloc、new等等)。

Monthly Archives

Pages

Powered by Movable Type 7.7.2

About this Entry

This page contains a single entry by Cnangel published on November 7, 2008 11:35 AM.

看fedora中的Counter-Strike was the previous entry in this blog.

使用iphone的几点心得 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.