这只是一个样本测试,我想把list Lb和La联合起来,不需要repeat元素。它不起作用,返回了-1073741510,我想可能是数组溢出,但我找不到问题所在
这是我的代码:

#include <stdio.h>

void Union(char *La, char *Lb);
int ListLength(char *L);
void GetElem(char *L, int i, char *e);
int LocateElem(char *L, char *e, int (*comp)(char a, char b));
int compare(char a, char b);
void ListInsert(char *, int, char *);

int main(){
    char *La;
    char *Lb;
    int i;
    for(i = 0; i <= 10; ++i){
        La[i] = i;
        Lb[i] = i + 5;
    }
    La[i] = '\0';
    Lb[i] = '\0';
    Union(La, Lb);
    for(i = 0; La[i] != '\0'; ++i){
        printf("%c\n", La[i]);
    }
    return 0;
}

//unite La and Lb without repeat elements
void Union(char *La, char *Lb){
    int La_length = ListLength(La);
    int Lb_length = ListLength(Lb);
    int i = 0;
    char *e;
    for(i; i<= Lb_length; ++i){
        GetElem(Lb, i, e);
        if(!LocateElem(La, e, compare))
            ListInsert(La, ++La_length, e);
    }
}

//caculate the length of L
int ListLength(char *L){
    int i;
    for(i = 0; *(L + i) != '\0'; ++i);
    return i;
}

void GetElem(char *L, int i, char *e){
    *e = *(L + i);
}

//search the element e in L, if exist return the location, else return 0
int LocateElem(char *L, char *e, int (*comp)(char a, char b)){
    int i;
    for(i = 0; *(L + i) != '\0'; ++i){
        if(comp(*(L + i), *e)) return i + 1;
    }
    return 0;
}

//compare the element a and b
int compare(char a, char b){
    if(a == b) return 1;
    return 0;
}

//if e doesn't exit in L, insert the e in L
void ListInsert(char *L, int i, char *e){
    int j;
    for(j = ListLength(L) - 1; j >= i; --j){
        *(L + j + 1) = *(L + j);
    }
    L[ListLength(L)] = '\0';
    *(L + i - 2) = *e;
}

最佳答案

首先,这是错误的:

char *La;
char *Lb;
int i;
for(i = 0; i <= 10; ++i){
    La[i] = i;
    Lb[i] = i + 5;
}

您需要为LaLb保留内存,例如,将它们声明为:
char La[12];
char Lb[12];

然后这个:
char *e;
for(i; i<= Lb_length; ++i){
    GetElem(Lb, i, e);

应改为:
char e;
for(; i<= Lb_length; ++i){
    GetElem(Lb, i, &e); /* better yet: e=Lb[i] */

最后,你最有可能通过使用<=而不是<作为for退出条件来循环一次太多。

关于c - 为什么此C编程无法正确运行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15708616/

10-11 22:10