在C函数中传递Char指针 [英] Passing Char pointer in C function

查看:457
本文介绍了在C函数中传递Char指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么下面程序的预期输出不是"hai"

I am wondering why the expected output for the below program is not "hai"

#include<stdio.h>
#include<conio.h>

void first(char*);
void first(char *s)
{
  printf("%u",s);
  s="hai";
}

int main()
{
 clrscr();
  char *t ="welcome";
  printf("%u",t);
   first(t);

 printf("%s",t);
  getch();
  return 0;
}

输出的结果是Welcome而不是Hai.

The output am getting is Welcome instead of Hai.

如果有人可以详细解释,那会更有用吗?

It would be more helpful, if somebody can explain in detail ?

推荐答案

C中的所有内容均按值传递.包括指针.因此,您已将一个内存地址(指针)传递给该函数,然后将其重新分配为指向另一位内存:指向您的"hai"字符串.原始指针t仍然很高兴地指向您的原始字符串"welcome". 当您传递t时,您传递了t按值指向的内存地址:该值已复制到参数/变量s.

Everything in C is passed by value. Including pointers. So you have passed a memory address (pointer) into the function and then re-assigned it to point at a different bit of memory: to point at your "hai" string. The original pointer t is still pointing happily to your original string "welcome". When you passed t in you passed the memory address that t points to by value: that value was copied to the argument/variable s.

这篇关于在C函数中传递Char指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆