打印字符串

时间:2019-06-04 07:47:29

标签: c pointers

我有3个问题:

  1. 为什么userHostPairs[count]=line会给出不希望的结果,如代码注释中所述?
  2. 为什么打印时程序会崩溃?
  3. 将userHostPairs作为arg传递给readEnv()以便可以在main中使用的方式是什么?
     #define MAX_HOSTS 100
     #define MAX_LINE_SIZE 100

     void readEnvList()
     {
            FILE *fp;

            char  line[MAX_LINE_SIZE];
            char* userHostPairs[MAX_HOSTS];

            if((fp = fopen("somefile", "r")) == NULL)
            {
                //ERR_StdReportAndReturn_2(OPIGN_FILE_FAILURE ,"write", schScriptFileName);
                printf("Failed to open the file\n");
            }

            int count =0;
            while (fgets(line, sizeof(line), fp) != NULL ) {
                    //userHostPairs[count]=line;  --Assignment like this gives undefined results. e.g. at the end of the loop userHostPairs[0] & userHostPairs[1] both contain the last fetched line from file.
                    strcpy(userHostPairs[count],line);
                    count++;
            }

            printf("%s",userHostPairs[0]); //CORE DUMP here

    }
    int main()
    {
            readEnvList();
    }

1 个答案:

答案 0 :(得分:2)

在您的代码中

  strcpy(userHostPairs[count],line);

您正试图写入指向不确定地址的统一指针(userHostPairs[count])。因此,在您的程序上下文中,内存位置为无效,并尝试写入无效的内存位置会调用undefined behavior

您需要

  • userHostPairs[count]中的每个分配有效的内存位置,以便每个元素指向一个有效的内存块(例如:使用malloc()或系列),然后在您使用strcpy()时使用已经完成了。
  • 使用strdup()完成复制。