所以,我的目标是创建一个线性搜索,但我得到了这一点,我有一个访问字符串的问题该结构中,我一直在使用一个txt文件,所以在linearSearch()
我试着这样做存储:C数组结构,试图访问数据,但是对于所有数组都提供相同的结果
printf("Name: %s \n", q.name[i]);
printf("Data: %d \n", q.data[i]);
的data
将是完美的,但name
将只打印出相同的名称为每个数组这将是最后一个项目我把它放入数组中。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char* name[10];
int data[10];
}Word;
//int bubblesort (Word word);
void linearSearch(char* name, Word q);
int main (int argc, const char *argv[]){
Word q;
char username[9]; /* One extra for nul char. */
int score;
int i = 0;
FILE *ifp, *ofp;
ifp = fopen("Data.txt", "r");
while (fscanf(ifp, "%s %d", &username, &score) == 2) {
q.name[i] = username;
printf ("Name: %s, I = %d \n", q.name[i], i);
q.data[i] = score;
printf ("Data: %d, I = %d \n", q.data[i], i);
i++;
}
linearSearch("Matt", q);
return EXIT_SUCCESS;
}
void linearSearch(char* name, Word q){
int i = 0;
int foundIt = 0;
int numNames = sizeof(&q.name);
while ((foundIt == 0) && (i <= numNames)){
printf("Name: %s \n", q.name[i]);
printf("Data: %d \n", q.data[i]);
if ((strcmp(name, q.name[i]) != 0)){
i = i + 1;
} else {
foundIt = 1;
}
}
if (foundIt == 1){
printf("Name found at position %d", i);
} else {
printf("Required person not found");
}
}
我现在有:strcpy(q.name [i],txtName);但它会出现分段错误? – MattSolo 2015-02-09 09:52:07
@MattSolo'q.name [i] = strdup(username);',当你完成后别忘了'释放'它们。 – WhozCraig 2015-02-09 09:52:55
@MattSolo在使用它之前,你需要使用'malloc()'将内存分配给'q.name [i]'。 – 2015-02-09 09:53:55