簡體   English   中英

在C中使用字符串數組

[英]Using String Arrays in C

我試圖將字符串存儲在數組中。 但是有一個錯誤。 我的代碼在這里:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <malloc.h>

const long long max_size = 2000;         // max length of strings
const long long N = 40;                  // number of closest words that will be shown
const long long max_w = 50;              // max length of vocabulary entries

int main(int argc, char **argv) {
  FILE *f;
  char st1[max_size];
  char kelimeler[max_size];     
  char *kelimelerim[max_size];  //string array initialization here
  char *bestw[N];
  char file_name[max_size], st[100][max_size];
  float dist, len, bestd[N], vec[max_size];
  long long words, size, a, b, c, d, cn, bi[100];
  char ch;
  float *M;
  char *vocab;

  strcpy(file_name, argv[1]);
  f = fopen(file_name, "rb");
  if (f == NULL) {
    printf("Input file not found\n");
    return -1;
  }


  fscanf(f, "%lld", &words);
  fscanf(f, "%lld", &size);
  vocab = (char *)malloc((long long)words * max_w * sizeof(char));
  for (a = 0; a < N; a++) bestw[a] = (char *)malloc(max_size * sizeof(char));
  M = (float *)malloc((long long)words * (long long)size * sizeof(float));
  if (M == NULL) {
    printf("Cannot allocate memory");
    return -1;
  }

  for (b = 0; b < words; b++) {
    a = 0;
    int sayac=0;
    while (1) {
      sayac++;  
      vocab[b * max_w + a] = fgetc(f);
      if (feof(f) || (vocab[b * max_w + a] == ' ')) {

        strcpy(kelimeler,&vocab[b * max_w + a-sayac+2]);  //gets the string here
        kelimelerim[b] = kelimeler;                      //and store it into string array here
        printf("%s %lld\n",kelimelerim[b],b); 
        sayac=0;
        break;

      }
      if ((a < max_w) && (vocab[b * max_w + a] != '\n')) 
        a++;
    }
    vocab[b * max_w + a] = 0;
    for (a = 0; a < size; a++) 
    fread(&M[a + b * size], sizeof(float), 1, f);
    len = 0;
    for (a = 0; a < size; a++) 
    len += M[a + b * size] * M[a + b * size];
    len = sqrt(len);
    for (a = 0; a < size; a++) 
    M[a + b * size] /= len;
  }
  fclose(f);

  int index;
  for (index = 0; index < words; index ++){
      printf("%s %d \n",kelimelerim[index ], index );
  }
  // here, the loop prints last string stored into array, for all indexes.       

我刪除了不重要的行。 當我運行上面的代碼並打印kelimelerim數組時,將為該數組的所有索引打印最后一個字符串。 我的錯誤在哪里? 請問你能幫幫我嗎。

您永遠不會初始化vocab ,因此以下內容具有未定義的行為

  vocab[b * max_w + a] = fgetc(f);

從那時起,所有賭注都關閉了。

您正在使用char *vocab; 作為未初始化的指針。 這導致未定義的行為。 您必須先初始化此指針,然后再將其與有效內存一起使用(例如,使用malloc )。

這個

kelimelerim[b] = kelimeler; 

不復制任何數據,而僅將kelimeler的地址存儲到kelimelerim[b] 如果隨后遍歷kelimelerim[b]的元素,則僅找到對kelimeler引用,並且隨着kelimeler每次迭代的重復使用,它包含最后讀取的字符串,然后依次為kelimelerim[b]每個元素打印kelimelerim[b]


更新

要解決此問題,可以用“字符串”數組代替kelimelerim[b] ,而不僅僅是指向字符串的指針,然后執行

strcpy(kelimelerim[b], kelimeler);

或通過執行以下操作動態創建kelimeler的真實副本:

kelimelerim[b] = strdup(kelimeler);

請注意,對於后一種情況,每次對strdup()調用都會從堆中分配內存,如果不再使用,則應通過在kelimelerim的每個元素上調用free()來釋放該kelimelerim

另外strdup()不是標准C,而是POSIX擴展。 您可能需要#define一些東西才能使用它。 有關詳細信息,請參見strdup()上的實現文檔。


如果strdup()不可用,則可能要使用以下命令:

#include <stdlib.h> /* for malloc() */
#include <string.h> /* for strcpy() */
#include <errno.h> /* for errno */

char * strdup(const char * s)
{
  char * p = NULL;

  if (NULL == s)
  {
    errno = EINVAL;
  }
  else
  {
    p = malloc(strlen(s) + 1);
    if (NULL == p)
    {
      errno = ENOMEM;
    }
    else
    {
      strcpy(p, s);
    }
  }

  return p;
}

暫無
暫無

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

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