小编Jha*_*ani的帖子

char*argv []和char**argv之间的差异,为main()的第二个参数

代码1

#include<stdio.h>

int main(int argc, char *argv[])
{
int j;
printf("%d", argv[1][0]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)

代码2

#include<stdio.h>

int main(int argc, char **argv)
{
int j;
printf("%d", argv[1][0]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)

CODE 1和CODE 2都提供相同的输出.但是CODE 1和CODE 2中主要功能的参数2是不同的.在编译时在数据部分上创建指针数组.argv是指针数组.然后我们应该在main函数中声明参数作为指向字符的指针,即**argv.在CODE 1中声明如何正确?

c arrays pointers parameter-passing argv

17
推荐指数
3
解决办法
4万
查看次数

为什么在CODE 1中出现分段错误?

代码1:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

main(int argc,char **argv)
{
    FILE *fp;
    char lineBuf[100],**p=NULL,temp[100];
    int cnt,j,i;
    if(argc!=2)
    {
        puts("ERROR:Invalid no.of arguments");
        return;
    }
    fp=fopen(argv[1],"r");
    if(fp==NULL)
    {
        printf("'%s' file doesn't exist\n",argv[1]);
    }
    cnt=0;

    while(fgets(lineBuf,100,fp))  //...........loop1
    {
        cnt++;
        p=realloc(p,sizeof(char*)*(cnt));
        if(p==NULL)
        {
            puts("memory unavailable");
            return;
        }

        p[cnt-1]=calloc(1,strlen(lineBuf));
        strcpy(p[cnt-1],lineBuf); //................statement1
    }

    fclose(fp);
    for(i=0;i<cnt;i++)
    {
        for(j=i+1;j<cnt;j++)
        {
            if(strcmp(p[i],p[j])>0)
            {
                strcpy(temp,p[i]);
                strcpy(p[i],p[j]);
                strcpy(p[j],temp);
            }
        }
    }

    fp=fopen(argv[1],"w");
    for(i=0;i<cnt;i++)
        fputs(p[i],fp);
    fclose(fp);
    puts("sorting done");
}
Run Code Online (Sandbox Code Playgroud)

代码2:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

main(int argc,char **argv)
{
    FILE …
Run Code Online (Sandbox Code Playgroud)

c file-read dynamic-memory-allocation file-pointer

-3
推荐指数
1
解决办法
107
查看次数