gpt4 book ai didi

c - 数组到C程序中的指针问题

转载 作者:太空宇宙 更新时间:2023-11-04 04:29:14 24 4
gpt4 key购买 nike

这是我正在处理的程序。

void primMST(int graph[N][N])
{
int parent[N] ; // Array to store constructed MST
int key[N]; // Key values used to pick minimum weight edge in cut
bool mstSet[N]; // To represent set of vertices not yet included in MST
int i, count, v;

// Initialize all keys as INFINITE
for (i = 0; i < N; i++)
key[i] = INT_MAX, mstSet[i] = false;

// Always include first 1st vertex in MST.
key[0] = 0; // Make key 0 so that this vertex is picked as first vertex
parent[0] = -1; // First node is always root of MST

// The MST will have N vertices
for (count = 0; count < N-1; count++)
{
// Pick thd minimum key vertex from the set of vertices
// not yet included in MST
int u = minKey(key, mstSet);

// Add the picked vertex to the MST Set
mstSet[u] = true;

// Update key value and parent index of the adjacent vertices of
// the picked vertex. Consider only those vertices which are not yet
// included in MST
for (v = 0; v < N; v++)

// graph[u][v] is non zero only for adjacent vertices of m
// mstSet[v] is false for vertices not yet included in MST
// Update the key only if graph[u][v] is smaller than key[v]
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}

// print the constructed MST
printMST(parent, N, graph);
}



int main()
{
int i, j;
int** graph = (int**) malloc(sizeof(int*)*N);
for(i=0;i<N;i++)
graph[i] = (int*) malloc(sizeof(int)*N);
FILE *fp;
fp = fopen("AdjacencyMatrix_of_Graph_G_N.txt","r");
char c;
for(i=0;i<N;i++) {
for(j = 0; j < N; j++) {
fscanf(fp, "%c ", &c);
graph[i][j] = c-'0';
}
}
for(i=0;i<N;i++) {
for(j=0;j<N;j++) {
printf("%d ",graph[i][j]);
}
printf("\n");
}
primMST(graph);
fclose(fp);
return 0;
}

我收到以下警告。

 C:\TURBOC3\BIN\PROJECT\MST.c:125:10: warning: passing argument 1 of 'primMST' from incompatible pointer type
primMST(graph);
^
C:\TURBOC3\BIN\PROJECT\MST.c:59:6: note: expected 'int (*)[30]' but argument is of type 'int **'
void primMST(int graph[N][N])
^


Compilation results...
--------
- Errors: 0
- Warnings: 2
- Output Filename: C:\TURBOC3\BIN\PROJECT\MST.exe
- Output Size: 132.0068359375 KiB
- Compilation Time: 0.48s

最佳答案

正如人们在这里评论的那样,int ** 与 int[][] 不同,这就是编译器提示的原因。

我还可以看到您正在动态分配 N 数组的大小,这有两个缺点:1. malloc 是一个相当昂贵的操作,调用它 N 次似乎没有必要。2.结果不会是连续的内存块。

假设 N 是一个#define,我建议在 main() 的堆栈上分配 graph[N][N] 而不是动态分配它。

关于c - 数组到C程序中的指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38316952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com