指向字符串 [英] pointer to string

查看:49
本文介绍了指向字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨。我们有以下计划..


#include< stdio.h>

#include< stdlib.h>

#include< string.h>

void fun(char *);

int main()

{

char * t =" hello";

fun(t);

printf("%s",t);

返回0;

}

虚假乐趣(char * r)

{

r =( char *)malloc(15);

strcpy(r," world");

printf("%s",r);

}


这里虽然我们已经传递了t的地址并在函数fun()中修改了它的值,但为什么没有反映出这种变化呢?请解释一下不同的类型这里使用的是内存吗?


Jerico

Hi.We have the following program..

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void fun(char*);
int main()
{
char *t="hello";
fun(t);
printf("%s",t);
return 0;
}
void fun(char *r)
{
r=(char*)malloc(15);
strcpy(r,"world");
printf("%s",r);
}

Here though we have passed the address of t and modifying its value in the function fun(),then why the change is not reflected?Please explain how different types of memory are used here?

Jerico

推荐答案


这里虽然我们已通过t
的地址
Here though we have passed the address of t



您尚未通过t的地址。 t的地址是


& t

你要通过



t

所以你传递的是绝对值。


你传递的是字符串文字的地址Hello因为这是包含的内容。

You have not passed the address of t. The address of t is

&t

you are passing

t

So you are passing t as am absolute value.

You are passing the address of the string literal "Hello" because this is what t contains.


ok。但是这个程序的内存分配怎么样?


Jerico
ok.But what about the memory allocation for this program?

Jerico

当你在mall()函数fun()里面你没有改变main()程序中指针t的值时 - 你需要传递t的地址(即& t)然后fun()函数头变成

void fun(char ** r)

其中参数r是指向char的指针


然后在fun()中正确地需要对dereferrence参数r进行其他更改 - 结果程序是
when you malloc() inside function fun() you don''t change the value of the pointer t in the main() program - to do so you need to pass the address of t (i.e. &t) and the fun() function header then becomes
void fun(char **r)
where the parameter r is a pointer to char *

other changes are then required in fun() to dereferrence parameter r correctly - the resultant program is
< span class =codeLinkonclick =Blur(this,this.parentNode.parentNode,getChildren(this),true);>展开 | 选择 | Wrap | 行号


这篇关于指向字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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