user2768747
user2768747

Reputation: 3

char pointer not returning proper value

In below code ptr prints "hello world" but temp is blank though I am passing temp as address.What can be possible reasons?

#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;
}

Upvotes: 0

Views: 243

Answers (1)

amdixon
amdixon

Reputation: 3833

This is due to the shadow parameter passing used in C.

On the inside of func, you are changing a local shadow of temp and making it point to "hello world" interned string. This does not change the original pointer temp in main context.

In order to change temp you must pass a pointer to temp in and adjust it:

#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;
}

Upvotes: 1

Related Questions