函数调用使用字符串文字而不是字符串变量C.

时间:2016-02-12 15:01:27

标签: c arrays string

我正在尝试从服务器中获取id中不同file1.txt代码的一些数据。如果我使用字符串文字d.id = "ABC",则调用fetchData(&d)可以正常工作,但如果我在从文件中读取它们后使用包含每个array[idx]的变量id则不起作用。任何人都可以给我一个关于我做错的提示(不知道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;
}

编辑:删除每个\n上的array[idx]个字符后,我的问题就解决了。

1 个答案:

答案 0 :(得分:0)

删除每个\n

上的array[idx]个字符后,我的问题就解决了