学习笔记 2.25

1.字符串赋值的问题

不能这么赋值,其他的几种都可以。

#include <stdio.h>
#include<string.h>
int main()
{
  char str[10]; 
  str = "China";
  printf("%s", str);
}

2.指针的某个问题

#include <stdio.h>
void func(char *q)
{
    char a[]="hello";
    q=a;
}
int main()  
{
    char *p;
    func(p);
    printf("%s\n",p);
} 

上述代码是错误的,要想修改用函数修改指针,就得像普通变量一样,要不用全局变量达到修改的目的,要不用指针直接改地址这里需要用到指针的指针。

#include <stdio.h>
void func(char **q)
{
    static char a[]="hello"; //静态数组,函数结束后不释放
    *q = a;
}
void main()
{
   char *p;
   func(&p); //传递p的地址
   printf("%s\n",p);
}

3.字符指针的问题

char *s;
s = "ABCDE";

可以这么赋值,但下面这么做:

char *s;
scanf("%s",s);

是不正确的,因为这里的指针s是一个野指针,没有指向一块开辟出的地址空间,系统随机了一个地址给s,对这个随机的地址的空间进行赋值是非法的,所以出错。
可以改成下面这样;

    char *s = (char *)malloc(100);
	scanf("%s", s);
	printf("%s", s); 
	free(s);

猜你喜欢

转载自blog.csdn.net/chengqidexue/article/details/87925687