1 # include <stdio.h> 2 # include <stdlib.h> 3 # include <time.h> 4 # include <string.h> 5 int main () 6 { 7 int _rand (int x); 8 int z,m; 9 char p; 10 11 char *q[100]={0}; 12 13 int a[100]; 14 FILE *fp = fopen ("name.txt","a+"); 15 if (fp == NULL) 16 { 17 printf ("文件打开失败"); 18 exit(1); 19 } 20 p = getc (fp); 21 if (p == EOF) 22 { 23 fseek (fp,0l,SEEK_SET); 24 z = 0; 25 printf ("文件中没有数据,或者数据没有按照规定格式输入! 请输入:"); 26 printf ("输入格式为n,姓名(ps:ctrl+z结束输入) "); 27 while (scanf ("%d %s",&a[z],*q+z) != EOF) 28 { 29 fprintf (fp,"%d %s ",a[z],*q+z); 30 z++; 31 } 32 } 33 else 34 { 35 fseek (fp,0l,SEEK_SET); 36 z = 0; 37 q[z]=(char *)malloc(100); 38 while (EOF != fscanf (fp,"%d %s",&a[z],q[z])) 39 { 40 41 printf ("%d %s ",a[z],q[z]); 42 z++; 43 q[z]=(char *)malloc(100); 44 } 45 } 46 for (m = 0;m < z;m++) 47 { 48 printf ("%d %s ",a[m],q[m]); 49 } 50 for (m = 0;m < z;m++) 51 { 52 free(q[m]); 53 } 54 55 m = _rand (z); 56 //printf ("%d %s",a[m],q+m); 57 } 58 int _rand (int x) 59 { 60 int a = 0; 61 srand (time(NULL)); 62 srand (rand()); 63 a = (rand()%x); 64 printf ("%d ",a); 65 return a; 66 }
name.txt 1 不是你 2 还是你 3 到底是不是你
1 # include <stdio.h> 2 # include <stdlib.h> 3 # include <time.h> 4 # include <string.h> 5 int main () 6 { 7 int _rand (int x); 8 int z,m; 9 char p; 10 11 char q[20][100]; 12 int a[100]; 13 FILE *fp = fopen ("name.txt","a+"); 14 if (fp == NULL) 15 { 16 printf ("文件打开失败"); 17 exit(1); 18 } 19 p = getc (fp); 20 if (p == EOF) 21 { 22 fseek (fp,0l,SEEK_SET); 23 z = 0; 24 printf ("文件中没有数据,或者数据没有按照规定格式输入! 请输入:"); 25 printf ("输入格式为n,姓名(ps:ctrl+z结束输入) "); 26 while (scanf ("%d %s",&a[z],q+z) != EOF) 27 { 28 fprintf (fp,"%d %s ",a[z],q+z); 29 z++; 30 } 31 } 32 else 33 { 34 fseek (fp,0l,SEEK_SET); 35 z = 0; 36 while(!feof(fp)) 37 { 38 fscanf (fp,"%d %s",&a[z],q+z); 39 z++; 40 } 41 /*while (EOF != fscanf (fp,"%d %s",&a[z],q+z)) 42 { 43 printf ("%d %s ",a[z],q+z); 44 z++; 45 }*/ 46 } 47 for (m = 0;m < z;m++) 48 { 49 printf ("%d %s ",a[m],q+m); 50 } 51 m = _rand (z); 52 //printf ("%d %s",a[m],q+m); 53 } 54 int _rand (int x) 55 { 56 int a = 0; 57 srand (time(NULL)); 58 srand (rand()); 59 a = (rand()%x); 60 printf ("%d ",a); 61 return a; 62 }
name.txt 1 不是你 2 还是你 3 到底是不是你
指针地址都是由操作系统分配的,不可以自己随意制定。
先用malloc函数分配一个足够大的内存空间,然后用scanf函数输入内容,不用这些空间后最好用free函数释放。部分代码
#include <stdlib.h> /* 使用malloc和free函数需要这个头文件 */
char *a[3];
a[0]=(char *)malloc(100); /* 算上结尾的 ,不超过100个字符 */
scanf("%s", a[0]);
free(a[0]); /* 使用解释后释放 */
C语言教材讲指针的部分有讲解。
*****************************
利用指针数组对字符串排序的程序如下:
void SortString(int n, char *str[])
{
char *c;
int i,j;
for(i=0;i<=n-2;i++)
for(j=0;j<=n-2-i;j++)
{
if(strcmp(str[j],str[j+1])>0)
{c=str[j];str[j]=str[j+1];str[j+1]=c;}
}
}
main()
{
int i;
char *lang[]={"China","France","English"};
SortString(3,lang);
for(i=0;i<3;i++)
printf(" %s ", lang[i]);
}
程序运行的结果为:
China
English
France
排 序前后指针数组的内存示意图如下。排序前lang[0],lang[1]和lang[2]保存的地址分别为"China","France" 和 "English"的首地址。排序结束后,3个字符串的内存情况没有发生变化,但指针数组里保存的指针顺序发生了变化:lang[1]指向 了"English",lang[2]指向了" France "。