在最短路径C代码中找出该分段故障11的原因

时间:2018-05-06 23:48:59

标签: c xcode

你好我一直在研究一个模拟最短路径算法的代码,但是我遇到了问题,我不断得到分段错误11错误这里是我的代码

#include <curses.h>
#include<math.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<math.h>


int size = 20;


#define IN 99



char *
strrev (char *str)
{
    if (!str) {
        fprintf (stderr, "%s() Error: invalid string\n", __func__);
        return NULL;
    }

    char *begin = str;
    char *end = str + strlen (str) - 1;
    char tmp;

    while (end > begin)
    {
        tmp = *end;
        *end-- = *begin;
        *begin++ = tmp;
    }

    return str;
}

int dijsktra(int costMatrix[][size],int source,int target)

{

    int distance[size],previous[size],IsSelected[size],i,m,minimum,s,d,j;
    memset(IsSelected, 0, size*sizeof(IsSelected[0]));
    char pathMatrix[size];

    for(i=1;i<size;i++)

    {

        distance[i] = IN;

        previous[i] = -1;

    }

    s = source;

    IsSelected[s]=1;

    distance[s] = 0;

    while(IsSelected[target] ==0)

    {

        minimum = IN;

        m = 0;

        for(i=1;i<size;i++)

        {

            d = distance[s] +costMatrix[s][i];

            if(d< distance[i]&&IsSelected[i]==0)

            {

                distance[i] = d;

                previous[i] = s;

            }

            if(minimum>distance[i] && IsSelected[i]==0)

            {

                minimum = distance[i];

                m = i;

            }

        }

        s = m;

        IsSelected[s] = 1;

    }

    s = target;

    j = 0;

    while(s != -1)

    {

        pathMatrix[j++] = s+65;

        s = previous[s];

    }

    pathMatrix[j]='\0';

    strrev(pathMatrix);

    printf("%s", pathMatrix);

    return distance[target];

}



int main(int argc, char** argv)

{
    int siz = argc;
    int id, port;
    int N;
    int costMatrix[N][N], i, j, ch, co;
    int *data;
    int startNode, source, target,x,y;

    id = atoi(argv[1]);

    port = atoi(argv[2]);

    N = argc-1;
    data=(int*)calloc(size,sizeof(int));


    for (i=1;i<siz;i++)
    {
        data[i]=atoi(argv[i]);
        printf("%d\n",data[i]);
    }
    printf("%d", N);


    printf("\tDIJKSRTRA's ALGORITHM\n\n");


   /* for(i=1;i< N;i++)
        printf("%d ", i);
        for(j=1;j< N;j++)
            printf("%d ", j);
            costMatrix[i][j]=IN;

    for(x=1;x< N;x++)

    {

        for(y=x+1;y< N;y++)

        {

            printf("The weight of the path between router port %d and %d : %d",x,y, atoi(argv[y]));



            costMatrix [x][y] = costMatrix[y][x] = atoi(argv[y]);

        }

        printf("\n");

    }*/
    printf("yo");
    startNode = atoi(argv[2]);
    source = atoi(argv[3]);

    target = atoi(argv[5]);

    co = dijsktra(costMatrix,N,startNode);

    printf("\nShortest Path: %d",co);

}

我评论了我的主循环,因为我认为它是由它引起的,但事实证明它不是。分段错误11发生在printf之前(&#34; yo&#34;);.任何想法或帮助将不胜感激

0 个答案:

没有答案