我正在尝试将一个char **从一个函数返回到main,所以我可以用它做一些东西,但是当我打印它时它会给我随机字符。我不知所措。
主要VV
// ./main < data/filelist.txt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hist.h"
int main(){
int count = 0;
int i;
char** files = read(&count);
displayList(files, count);
char** array = splitFiles(files, count);
printf("IN MAIN: array[0] - %s\n", array[0]);
Histogram* p;
printf("here\n");
int histArrayCount = calcHistogram(&array[0], &count, &p);
printf("here\n");
displayHistogram(p, histArrayCount);
printf("here\n");
}
hist.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hist.h"
int calcHistogram (char** a, int* count, Histogram** q) {
int i, k;
int j = 0;
int histArrayCount = 0;
Histogram* p = (Histogram*)malloc((*count) * sizeof(Histogram));
for (k = 0; k < *count; k++) {
p[k].num = "1";
p[k].freq = 0;
}
for (i = 0; i <= *count; i++) {
while ((strcmp(p[j].num, "1") != 0) && (strcmp(p[j].num, a[i]) != 0)) {
j++;
}
if (strcmp(p[j].num, "1") == 0) {
p[j].num = a[i];
p[j].freq = 1;
histArrayCount++;
}
else if ((strcmp(p[j].num, a[i]) == 0)) {
p[j].freq += 1;
}
else {
printf("ERROR\n");
}
j = 0;
}
*q = p;
return histArrayCount;
}
void displayHistogram (Histogram* p, int histArrayCount) {
int i;
for (i = 0; i < histArrayCount - 1; i++) {
printf("value %s: freq %d\n", p[i].num, p[i].freq);
}
printf("\n");
}
char** splitFiles(char** files, int count) {
int i;
char** array = (char**)malloc((count)*sizeof(char*));
FILE* fp;
int c = 0;
for(i = 0; i < count; i++) {
char buff[255];
fp = fopen(files[i], "r");
array[i] = fgets(buff, 255, (FILE*)fp);
printf("%d : %s\n", i, buff);
}
printf("array[0] = %s\n", array[0]);
return array;
}
void displayList(char** a, int c) {
int i;
for (i = 0; i < c; i++) {
printf("File %d: %s\n", i, a[i]);
}
printf("\n");
}
char** read(int* c){
int count = 0;
int i;
char** a = (char**)malloc(100*sizeof(char*));
for (i = 0; i< 100; i++) {
a[count] = (char*)malloc(100*sizeof(char));
count++;
}
count = 0;
int endOfFile = scanf("%s", a[count]);
while (endOfFile != EOF) {
count++;
endOfFile = scanf("%s", a[count]);
}
*c = count;
return a;
}
当我在这里的索引0处打印数组时,它给出了实际存在的内容,但是当我在main中执行相同的操作时它却没有。它给了我三个随机字符。
hist.h
typedef struct Histogram {
char* num;
int freq;
} Histogram;
char** read(int* c);
void displayList(char** a, int c);
int calcHistogram (char** a, int* c, Histogram** p);
void displayHistogram (Histogram* a, int histArrayCount);
char** splitFiles (char** files, int count);