0

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

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

The term shadow parameter passing is unusual terminology — certainly not the standard terminology. But the basic diagnosis is correct: you pass the pointer by value, and change the local copy of the pointer in the function without changing the pointer in the calling code. If you want to change a pointer in a function, you have to pass the address of the pointer to be changed to the function, just as if you want to change an int passed to a function, you have to pass the address of the int to be changed to the function.
@JonathanLeffler yep; the parameter is passed as a shadow (or copy). i think the usual terminology might be by-value, which is a bit misleading, as it copies the value and doesnt change it..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.