所有数组元素在C中都是相同的fget? [英] all array elements are the same fgets in C?

查看:57
本文介绍了所有数组元素在C中都是相同的fget?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当前我的程序使用这样的硬编码数组:

So currently my program uses a hard-coded array like this:

char *array[] = {"array","ofran","domle","tters", "squar"}

基本上n个字符串 n length(一个n * n网格)。然后,我将这些值视为2D数组。因此,我将访问array [y] [x]并使用相应的ASCII进行比较操作和数学运算。

Basically n strings of n length "an n*n grid. I then treat the values like a 2D array. So I will access array[y][x] and do comparison operations and math using the corresponding ASCII.

我想允许在程序中实现各种大小(n * n)(最多32个)的文本文件,而不是对其进行硬编码,但是我在使用fgets时遇到了问题。

I wanted to allow text files of various sizes (n*n) (up to 32) be implemented in my program instead of hard coding it. But am having issues with using fgets.

我当前用于获取和存储文件信息的函数如下:

My current function for getting and storing the file information looks like this:

char *array[32];
char buffer[32];
FILE *fp = fopen("textfile.txt","r");

int n = 0;
while(fgets(buffer, 32, fp)){
    array[i] = buffer;
    n++;
}
fclose(fp);

,但是 array的所有值都相同(它们是最后一个字符串)。以上。如果我将array [0]打印到array [4],我将从代码中得到

but all values of "array" are the same (they are the last string). So with the example values above. If I printed array[0] to array [4] I get

squar
squar
squar
squar
squar

期望值:

array
ofran
domle
tters
squar


推荐答案

array [i] = buffer 只是将相同的指针分配给 array 的所有元素。您需要在此处动态分配内存:

array[i] = buffer just assigns the very same pointer to all elements of array. You need dynamic memory allocation here:

char *array[32];
char buffer[32];
FILE *fp = fopen("textfile.txt","r");

int n = 0;
while(fgets(buffer, 32, fp)){
    array[i] = strdup(buffer);  // allocate memory for a new string
                                // containing a copy of the string in buffer
    n++;
}
fclose(fp);

为简洁起见,此处未进行错误检查。另外,如果输入文件包含多于32行,您也会遇到麻烦。

No error checking is done here for brevity. Also if the input file contains more than 32 lines you'll run into trouble.

如果 strdup 不存在在您的平台上:

if strdup does not exist on your platform:

char *strdup(const char *str)
{
  char *newstring = malloc(strlen(str) + 1);  // + 1 for the NUL terminator
  if ( newstring )
    strcpy(newstring, str);
  return(newstring);
}

为简便起见,这里也没有进行错误检查。

Again no error checking is done here for brevity.

这篇关于所有数组元素在C中都是相同的fget?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆