char指针没有返回正确的值

时间:2013-12-07 03:06:26

标签: c pointers character

在下面的代码中,ptr print" hello world"但是虽然我正在传递临时地址,但临时是空白的。可能的原因是什么?

#include <stdio.h>
#include <string.h>
#include <malloc.h
unsigned char temp[1024];

void func(unsigned char *ptr)
{
  const char* x = "hello world";

  ptr = (unsigned char*) x;

  printf("ptr=%s\n",ptr);
}

int main ()
{


  func(temp);
  printf("temp=%s\n",temp);

  return 0;
}

1 个答案:

答案 0 :(得分:1)

这是由于C.

中使用的 shadow参数传递

func的内部,您正在更改temp的本地阴影并使其指向&#34; hello world&#34;实习字符串。这不会更改main上下文中的原始指针temp。

要更改temp,您必须将指针传递给temp并进行调整:

#include <stdio.h>
#include <stdlib.h>

void func(unsigned char **ptr)
{
  const char *x = "hello world";
  *ptr = (unsigned char*) x;
}

int main ()
{
  unsigned char *temp;
  func(&temp);
  printf("temp=%s\n",temp);
  return 0;
}