问题描述
我正在写一个小程序如下:
#include< stdio.h>
#include< string.h>
#include< stdlib.h>
void f(char *);
int main()
{
char * p;
strcpy(p," HELLO WORLD");
printf("%s",p);
f(p);
printf(在主要后面的p是%s,p);
返回0;
}
void f(char * p)
{
p ++;
}
执行此程序后我得到了输出
HELLO WORLDp之后的主要是HELLO WORLD
但我的意图是得到输出为
HELLO WORLDp之后的主要是ELLO WORLD
这意味着在函数f中它的增加p。
仍然在函数调用p保持不变之后..如何编写函数以便得到我想要的结果。谢谢。
你很幸运,你有任何输出。你要将一个字符串复制到
p指向的地方,但是p并没有指向任何东西,所以你要复制那个字符串
到一个黑暗未定义行为规则的未知区域。
更重要的是(在您解决了上一期之后):C按值传递参数
,即你的函数修改指针p的副本,而不是指针的
值本身。
亲切的问候,
Jos
I am writing a small program as below:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void f(char *);
int main()
{
char *p;
strcpy(p,"HELLO WORLD");
printf("%s",p);
f(p);
printf("p after in main is %s",p);
return 0;
}
void f(char *p)
{
p++;
}
after executing this program I am getting the output
HELLO WORLDp after in main is HELLO WORLD
But my intension is to get the output as
HELLO WORLDp after in main is ELLO WORLD
That means in function f its increasing p.
Still after the function call p remains unchanged.. How can I write the function so that I will get my desired result. Thanks.
You''re lucky that you got any output at all. You''re copying a string to where
p points to, but p doesn''t point to anything at all so you''re copying that string
to a dark unknown area where undefined behaviour rules.
More to the point (after you''ve solved the previous issue): C passes parameters
by value, i.e. your function modifies a copy of the pointer p, not the pointer''s
value itself.
kind regards,
Jos
这篇关于请帮帮我,我在函数调用中很困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!