gpt4 book ai didi

c - 在 C 中使用字符串数组

转载 作者:太空宇宙 更新时间:2023-11-04 02:46:43 25 4
gpt4 key购买 nike

我试图将字符串存储在数组中。但是有一个错误。我的代码在这里:

#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,所以下面有undefined behaviour :

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

从那时起,所有的赌注都落空了。

关于c - 在 C 中使用字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26573977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com