1

我正在嘗試使用雙指針結構作爲結構數組。 當我在main()中寫入完整的代碼時,它工作正常。 下面是工作代碼:訪問函數中的雙指針結構

[email protected] cat struct2.c 

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 
#include <malloc.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <signal.h> 

typedef struct conn_s{ 
    int no; 
    char name[32]; 
}conn_t; 
int main(){ 
    int i=0, n; 
    conn_t **connections; 
    printf("How many students?\n"); 
    scanf("%d", &n); 
    for(i=0;i<n;i++){ 

    connections[i] = (conn_t*)malloc(sizeof(conn_t)); 
      printf("Enter no,name of student\n"); 

      scanf("%d%s", &connections[i]->no, &connections[i]->name); 
    } 

    printf("The student details you entered are"); 
    for(i=0;i<n;i++){ 
      printf("%d  %s", connections[i]->no, connections[i]->name); 
      free(connections[i]); 
    } 

    return 1; 
} 

[email protected] 
[email protected] ./struct2 
How many students? 
3 
Enter no,name of student 
1 pavan 
Enter no,name of student 
2 suresh 
Enter no,name of student 
3 ramesh 
The student details you entered are1  pavan2  suresh3  ramesh 

但是,當我在一個函數中使用相同的代碼就無法正常工作。

[email protected] cp struct2.c struct1.c 
[email protected] vi struct1.c 

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 
#include <malloc.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <signal.h> 

typedef struct conn_s{ 
    int no; 
    char name[32]; 
}conn_t; 
int data(){ 
    int i=0, n; 
    conn_t **connections; 
    printf("How many students?\n"); 
    scanf("%d", &n); 
    for(i=0;i<n;i++){ 

    connections[i] = (conn_t*)malloc(sizeof(conn_t)); 
      printf("Enter no,name of student\n"); 

      scanf("%d%s", &connections[i]->no, &connections[i]->name); 
    } 

    printf("The student details you entered are"); 
    for(i=0;i<n;i++){ 
      printf("%d  %s", connections[i]->no, connections[i]->name); 
      free(connections[i]); 
    } 

    return 1; 
} 

int main(){ 
    data(); 
return 1; 
} 
Entering Ex mode. Type "visual" to go to Normal mode. 
:wq 
"struct1.c" 41L, 874C written 
[email protected] gcc -o struct123 struct1.c 
[email protected] ./struct123 
How many students? 
3 
Segmentation fault 
[email protected] 

你能幫我理解這個問題嗎?

+0

有人喜歡VIM :) – Ben

+1

*始終*使用'GCC -Wall -Werror '。你的生活會更好,更好。 –

+0

我也建議'-Wextra',以及'-std = gnu99 -pedantic'。 – melpomene

回答

2
connections[i] = ... 

該行讀取未初始化的變量connections。這會在兩個程序中導致未定義的行爲。 (也就是說,任何事情都有可能發生,包括看似「正常工作」。)

您可以通過循環之前做

connections = malloc(n * sizeof *connections); 

解決這個問題。


順便說一句:

  • <malloc.h>是不是一個標準的頭
  • 你不應該投malloc
  • 你應該檢查錯誤(scanf可以失敗,可以malloc失敗等)
  • 1不是便攜式退出狀態/ main返回值(1表示unix和windows上有錯誤,但唯一的便攜代碼爲0EXIT_SUCCESS,成功爲EXIT_FAILURE)。
  • 傳遞&connections[i]->namescanf%s是錯誤的:%s需要char *&connections[i]->namechar (*)[32](來解決這個問題,刪除&
+0

在實時編碼中,我不知道我需要存儲多少個條目。 – pavan