簡體   English   中英

函數調用適用於字符串文字,但不適用於字符串變量C

[英]function call work with string literal but not with a string variable C

我正在嘗試從服務器獲取一些數據,用於file1.txt不同id代碼。 如果我使用字符串文字d.id = "ABC"則調用fetchData(&d)可以正常工作,但是如果我從文件中讀取它們后使用包含每個id的變量array[idx]則無法正常工作。 誰能給我一個關於我做錯了什么的提示(而無需了解fetchData()的內部fetchData() )? 我正在學習C,請耐心等待。

file1.txt的內容如下所示:

ABC
DEF
...

我的代碼如下:

/*    #include "myapi.h" */ //fetchData

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

typedef struct param {
        char *id;
    } param_t;

int countlines(char filename[])
{
  // count the number of lines in the file called filename                                    
  FILE *fp = fopen(filename,"r"); 
  int ch=0;
  int lines=0;

  while(!feof(fp))
    {
      ch = fgetc(fp);
      if(ch == '\n')
    {
      lines++;
    }
    }

  fclose(fp);
  return lines;
}

int main()
{

  char filename[] = "file1.txt";
  int N = countlines(filename);

  // open the file for reading
  FILE *file = fopen(filename, "r");

  // make sure the file opened properly
  if(NULL == file)
    {
      fprintf(stderr, "Cannot open file: %s\n", filename);
      return 1;
    }

  size_t buffer_size = 10;

  /* create an array of char pointers */
  char **array = malloc(N * buffer_size * sizeof(char*));

  /* allocate space for each string: */
  int line_number = 0; 
  for (line_number = 0; line_number < N; ++line_number) {
    array[line_number] = (char *)malloc(buffer_size+1);
  }

  // read each line into the string array
  line_number = 0;
  while(-1 != getline(&(array[line_number]), &buffer_size, file))
    ++line_number;

  fclose(file);

  param_t d, dempty;

  memset(&d, 0, sizeof d);
  memset(&dempty, 0, sizeof dempty);

  int idx;
  for (idx=0; idx<N; idx++)
    {

      if(!(d.id = malloc(strlen(array[idx]) + 1))) 
    {
      //allocation failed
    }

      /* if initialized with string literals the data request works */
      d.id= "ABC";

      /* if d is initialized with a variable the data request doesn't work */
      // strcpy(d.id, array[idx]);

      fetchData(&d);

      /* reset structure*/
      d = dempty; 

    } 

  /*free memory */
    for (;idx>=0;idx--)
        free(array[idx]);
    free(array);

  return 0;
}

編輯:刪除每個array[idx]上的\\n字符后,我的問題得到解決。

在刪除每個array[idx]上的\\n字符后,我的問題得到解決array[idx]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM