c++指针作为形参常见问题--2

本文通过案例分析了C++中使用指针作为参数时值传递的问题,特别是在创建链表的过程中。错误案例1展示了尽管采用了值传递方式,但由于头指针在子函数中被修改的副本并未影响原头指针,导致链表未正确构建。正确的案例则说明了在创建链表时,值传递方式如何生效,以及如何通过址传递或引用传递来解决头指针更新的问题。
摘要由CSDN通过智能技术生成

【案例1】【错误案例】

#include<iostream>
#include<cstddef>
#include<cstdio>
#include<cstdlib>
#include<cstring>

using namespace std;
 
typedef struct charlink 
{
	char ch;
	struct charlink *next;
} CharLink;

void insertCharLink(CharLink *q,const char *chr)
{
    printf("#3 void insertCharLink q %p\n",q);
	CharLink *t = (CharLink*)malloc(sizeof(CharLink));
	t->ch = *chr;
	t->next = NULL;
	q->next = t;
	q = q->next;
	printf("#4 void insertCharLink q %p\n",q);
	
}

int main()
{
    const char str1[] = {'2','3','5','\0'};
    CharLink *p = (CharLink*)malloc(sizeof(CharLink));
    p->next=0;
    p->ch = 'Q';
    CharLink *h = p;
    int i=0;
    printf("#1 main--initial p %p\n",p);
    printf("#1 main--initial h %p\n",h);
    cout<< "#1 p->ch " << p->ch<<endl;
    while(str1[i])
    {
    	printf("#2--%d main--while p %p\n",i+1,p);
    	printf("#2--%d main--while h %p\n",i+1,h);
    	printf("#2--%d main--while p->ch %c\n",i+1,p->ch);
        printf("#2--%d main--while h->ch %c\n",i+1,h->ch);
        if(h->next)
            printf("#2 h->next->ch %c\n",h->next->ch);
    	insertCharLink(p,&str1[i]);
    	++i;

	}
	printf("# h->ch %c\n",h->ch);
	printf("# h->next->ch %c\n",h->next->ch);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值