指针的赋值

来源:百度知道 编辑:UC知道 时间:2024/07/06 23:51:56
#include <stdio.h>
main()
{
char *a[20],*p,*b[20];
int i,n,len,count=0,j=0,k=0;
printf("\nplease input the number of names less than 20:\n");
scanf("%d",&n);
//输入字符串并统计以M开头的串
for(i=0;i<n;i++)
{
scanf("%s",a[i]);
if(('M'-*a[i])==0)
{
b[j++]=a[i];
count++;
}
}
p=a[0];
k=0;
//寻找最大串
for(i=0;i<n;i++)
{
len=strlen(a[i]) ;

if(k<len)
{k=len;
strcpy(p,a[i] );
printf("****%s****",p);}

}
//输出结果
printf("the names start with M have %d intotal\n",count);
printf("as shown in the following:\n");
for(i=0;i<count;i++)
printf("%s\n",b[i]);
printf("\nthe maximum is %s",p);
}
希望前辈指教一下,为什么上述程序编译后有运行结果,直接运行输出是NULL呢??指针赋值是在什

char *a[20],*p,*b[20];
这些只是指针,它们没有数据存储单元。

你要么动态分配存储单元给它们,或者让它们指向别的现有变量的单元地址。否则
scanf("%s",a[i]); 数据没地方存放。

这样的编程错误已经见过n次了,问题出在尚未初始化指针变量就直接使用。
#include <string.h>
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

void main()
{
char *a[20],*p,*b[20];
int i,n,len,count=0,j=0,k=0;
printf("\nplease input the number of names less than 20:\n");
scanf("%d",&n);
//输入字符串并统计以M开头的串
for(i=0;i<n;i++)
{
a[i] = (char *)malloc(sizeof(char) * 50);
scanf("%s",a[i]);
if(('M'-*a[i])==0)
{
b[j++]=a[i];
count++;
}
}

//寻找最大串
for(i=0;i<n;i++)
{
len=strlen(a[i]) ;

if(k<len)
{
k=len;
p = a[i];
printf("****%s****",p);
}

}
//输出结果