(十四)C语言杂项

1、printf()输出某个值的地址

C语言中要输出地址需要16进制的方式输出,需要用%x格式。

要输出某个值的地址写成printf("%x",&变量);若变量为指针时,则应写成printf("%x",指针)

2、C语言中指针变量如何向函数中传递

指针变量存储的是地址,所以在函数调用的时候能否将指针变量传递给函数。

void getm(char* p) {
  p = (char*)malloc(100);
  printf("p:%x\n", p);
}

void test() {
  char* str = 0;
  getm(str);
  printf("str:%x\n", str);
  strcpy(str, "hello world");
}

代码会直接奔窥。str为局部变量,当传递给函数时,函数不能真正使用str,用的只是str的一个备份,str的值不变。此处str的值仍然为null,malloc分配的内存地址并没有赋给str。

解决方法:

1)使用return返回地址

char* getm() {
  char* p = (char*)malloc(100);
  printf("p:%x\n", p);
  return p;
}

void test() {
  char* str = 0;
  str=getm();
  printf("str:%x\n", str);
  strcpy(str, "hello world");
}

2)使用二级指针

void getm(char** p) {
  *p = (char*)malloc(100);
  printf("p:%x\n", *p);
}

void test() {
  char* str = 0;
  getm(&str);
  printf("str:%x\n", str);
  strcpy(str, "hello world");
}

你可能感兴趣的:(C++,c语言,开发语言)