0
#include<stdio.h>   
int main()  
{    
    char *arg[10],*c;  
    int count=0;  
    FILE *fp,*fq;  
    printf("Name of the file:");  
    scanf("%s",arg[1]);  
    fp=fopen(arg[1],"w");  
    printf("\t\t%s",arg[1]);  
    printf("Input the text into the file\n");  
    printf("Press Ctrl+d to the stop\n");  
    while((*c=getchar())!=EOF)  
    {  
            fwrite(c,sizeof(char),1,fp);  
            count++;  
    }  
    return 0;  
}  
4

4 回答 4

3

更改此行

char *arg[10],*c;

char arg[1000],c;

这条线

scanf("%s",arg[1]);  

scanf("%s",arg);  

而这条线

while((*c=getchar())!=EOF)

while((c=getchar())!=EOF)

解释:

char *c;不是一个字符。它是一个字符的指针。它一开始只是指向一个随机的内存位,它通常会充满随机数据——不管是最近写在那里的。

char c; 一个字符。

同样的事情也适用于char *arg[10]. 这是一个由十个指针组成的数组。它们指向随机存储器,里面充满了随机数据。

注意:我的更改不是最佳实践。如果有人要输入 1000 个字符或更长的文件名,您会写在arg缓冲区的末尾。根据您的操作,这可能是一个安全漏洞。

于 2011-04-16T14:27:38.160 回答
1
char *arg[10] ;

arg是 char 指针数组。您需要malloc在输入之前为它们分配内存位置 -

scanf("%s",arg[1]); // arg[1] is not assigned to point to any memory location
                    // and is what causing the segmentation fault.

就这样——

arg[1] = malloc( stringLengthExpectedToEnter + 1 ) ; // +1 for termination character

其他数组元素也应该这样做(或)只需更改char*arg[10]char arg[10]并确保只输入 9 个字符。


我认为您在指针普通变量之间感到困惑。

int *ptr;

ptr是可以保存整数变量地址的变量。为ptr变量分配内存以保存整数地址。而已。ptr处于未初始化状态并且没有指向(或)可能指向垃圾的地方。取消引用未初始化指针的行为是未定义的,如果它给出了segmentation-fault,你就足够幸运了。

现在,您需要使用malloc.

ptr = malloc( sizeof(int) ) ; // Allocates number of bytes required to hold an
                              // integer and returns it's address.

因此,ptr现在指向从可以保存整数的空闲存储中获取的内存位置。从免费存储中获取的这些位置必须使用释放free,否则您会遇到内存泄漏的经典问题。声明时将指针初始化为NULL是一种很好的做法。

int *ptr = NULL ;

希望能帮助到你 !

scanf("%d", ptr) ; // Notice that & is not required before ptr. Because ptr 
                   // content is address itself.

一个正常的可变故事完全不同。宣布时 -

int var ;

分配内存var以保存整数。因此,您可以直接为其分配一个整数。

于 2011-04-16T14:27:06.187 回答
1

char *arg[10];

您定义了一个包含 10 个指向 char 的指针的数组,但您没有初始化它的元素。arg[0], arg[1], ..., arg[9] 都将具有未定义的值。

然后,您尝试在其中一个未定义的值中输入一个字符串。幸运的是,您遇到了分段错误。如果你不走运,你的程序可能会格式化你的硬盘

于 2011-04-16T14:28:47.597 回答
0
#include<stdio.h>   
int main()  
{    
   char arg[10],c;  
   int count=0;  
   FILE *fp;  
   printf("Name of the file:");  
   scanf("%s",arg);  
   fp=fopen(arg,"w");  
   printf("\t\t%s",arg);  
   printf("Input the text into the file\n");  
   printf("Press Ctrl+d to the stop\n");  
   while((c=getchar())!=EOF)  
   {  
        fwrite(&c,sizeof(char),1,fp);  
        count++;  
   }

   if(fp != NULL){
      fclose(fp);
      fp = NULL;
   }
   return 0;  
}  
于 2012-10-19T19:55:57.127 回答