我简单地做一个字符数组str.later我犯了一个char *p
它简单地指向它,我可以访问(行程)从开始到结束str
,我可以操纵使用p
的str
,意味着 p[i]='x';
(其中,i:一有效索引,x:任何字符)是否有效?实际上我试过它是工作,我的问题是没有必要使用malloc给它记忆(即p = malloc(l * sizeof(char));)。可以使用char指针来操作它指向的char数组吗?
#include<stdio.h>
#include<string.h>
int main()
{
char str[20];
char *p;
scanf("%s",str);
printf("%s\n",str);
int l=(int)strlen(str);
// printf("l= %d\n",l);
//p=str;
//p=malloc(l*sizeof(char));
p=str;
int i;
for(i=0;i<l;++i)
printf("%c-",*(p+i));
printf("\nNow p=%s\n",p);
p[1]='x'; // it is valid , but difficult to understand?? we didnot give it memory,but it can manipulate the str as well.
printf("After changes made\n",p);
printf("p=%s\n",p);
printf("str=%s\n",str);
return 0;
}
是的,这是好的。 'char str [20];'分配20个字节,你用'p'指向那个分配。 – 2014-10-01 11:38:52
我认为解释没问题*'* p'必须指向有效内存*。 – usr2564301 2014-10-01 11:38:55
'p = str'表示'p'拥有'char'数组'str'的基地址。 – 2014-10-01 11:39:34