遵循代码时遇到了一个奇怪的问题,由于某种原因,buff在while循环的每次迭代中都会覆盖arr。代码旨在逐行从文本文件中读取,每行读取拖曳单词并在"arr"数组中搜索每个单词。如果找到将返回其索引,如果没有,它将将其存储在下一个可用位置并返回索引。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*given a new word t, it searches in arr for it, if found returns the index
if not found returns first availble index and stores it */
int searchIndex(char * t,char **arr, int n){
int i;
for(i=0;i<=n;i++){
if(arr[i]==NULL){
arr[i]=t;
return i;
}
if(strcmp(arr[i],t)==0)
return i;
}
}
int main(int argc, char* argv[])
{
char *token =(char *)malloc(sizeof(char)) ;
const char s[2] = " ";
FILE *fp;
char buff[255];
int index;
int V=3; // Number of vertices in graph
char ** arr = (char **)malloc(sizeof(char*)*V) ;
fp = fopen(argv[1], "r");
//loop reads words from file and assigns each word a uniqe index in arr
while(fgets(buff, 255, (FILE*)fp))
{
printf("arr in begining of iteration: n");
printf("%s t",arr[0]);
printf("%s t",arr[1]);
printf("%s t",arr[2]);
printf("n");
token = strtok(buff, s);
printf("first token read: %s t",token);
index = searchIndex(token,arr,V);
printf("first tokens index: %d t",index);
printf("n");
token = strtok(NULL, s);
printf("second token read: %s t",token);
index = searchIndex(token,arr,V);
printf("second tokens index: %d t",index);
printf("n");
printf("arr at end of iteration: n");
printf("%s t",arr[0]);
printf("%s t",arr[1]);
printf("%s n",arr[2]);
printf("n");
}
fclose(fp);
return 0;
}
这里
char ** arr = (char **)malloc(sizeof(char*)*V) ;
您分配V
指针。
在这里,您将已分配的内容以及arr
指向的元素数量传递给
index = searchIndex(token,arr,V);
在searchIndex()
中,您在分配时再迭代一个元素:
int searchIndex(char * t,char **arr, int n){
int i;
for(i=0;i<=n;i++){
要少修复一个迭代器:
int searchIndex(char * t, char ** arr, int n) {
int i;
for (i=0; i<n; i++) {
在每次迭代中,您从文件中读入buff
,在空间上标记化buff
拆分,然后在arr
中存储指向标记化字符串的指针。注意:由于您存储的是指向buff
内位置的指针,因此下次读入buf
可能会覆盖arr
中的数据。
searchIndex()
您需要将令牌的副本存储在 arr
中。您可以使用strdup()
为此。此外,您在搜索循环中迭代了 1 次太多,这是另一个问题,但不是直接导致覆盖arr
的问题。另一件事,一旦arr
已满,函数就不会返回显式值(它可以是任何东西!) - 您可以返回 -1 来指示完整的数组:
int searchIndex(char * t,char **arr, int n) {
int i;
for(i=0; i<n; i++) {
if (arr[i] == NULL) {
arr[i] = strdup(t);
return i;
}
if (strcmp(arr[i], t) == 0)
return i;
}
return -1;
}