當我使用 vector_read() 函式或通過使用 vector_init_zero() 將其初始化為零來讀取第二個向量時,我得到了分段錯誤。我已經搜索了很多仍然沒有得到它為什么會發生的答案。如果我只使用一個指標并且不將其初始化為 0 它作業正常。每個其他函式都可以與結構指標的單個變數一起正常作業。
#include <stdio.h>
#include <stdlib.h>
typedef struct vector_s
{
int dim;
float *data_ptr;
} vector_type;
/* Allocate and initialize to 0 a vector with the given dimension */
void vector_init_zeros(vector_type *v_ptr, int dim)
{
v_ptr->dim = dim;
v_ptr->data_ptr = (float *)calloc(dim, sizeof(float));
#ifdef DEBUG
if (v_ptr->data_ptr == 0)
{
printf("vector_init_zeros error: calloc returned a null ptr\n");
exit(1);
}
#endif
}
/* Free up a vector that was allocated using vector_init_zeros */
void vector_deinit(vector_type *v_ptr)
{
v_ptr->dim = 0;
free(v_ptr->data_ptr);
v_ptr->data_ptr = 0;
}
/* Attempt to read a vector from stdin. */
/* Returns 1 if read successful and 0 otherwise */
int vector_read(vector_type *v_ptr)
{
int i;
float next;
for (i = 0; i < v_ptr->dim; i )
{
if (scanf("%g\n", &next) != 1)
{
return 0;
}
v_ptr->data_ptr[i] = next;
}
return 1;
}
/* w = u v */
void vector_add(vector_type *u_ptr, vector_type *v_ptr,
vector_type *w_ptr)
{
int i;
for (i = 0; i < v_ptr->dim; i )
{
w_ptr->data_ptr[i] = u_ptr->data_ptr[i] v_ptr->data_ptr[i];
}
}
/* v = cv */
void vector_scalar_mult(vector_type *v_ptr, float c)
{
int i;
for (i = 0; i < v_ptr->dim; i )
{
v_ptr->data_ptr[i] = v_ptr->data_ptr[i] * c;
}
}
/* print the compondents of the given vector */
void vector_print(vector_type *v_ptr)
{
int i;
for (i = 0; i < v_ptr->dim; i )
{
printf("%f ", v_ptr->data_ptr[i]);
}
printf("\n");
}
int main()
{
int dim;
int count = 0;
if (scanf("%d", &dim) != 1)
{
printf("Error reading the vector dimension from stdin\n");
exit(1);
}
vector_type *s,*t;
vector_init_zeros(s, dim);
vector_init_zeros(t, dim);
vector_read(s);
vector_read(t);
}
uj5u.com熱心網友回復:
在main()你宣告sand的地方t,你永遠不會初始化它們。您可以將它們宣告為結構變數并將它們的地址傳遞給使用&'address of'運算子的函式,或者使用malloc()andfree()或等價物分配和釋放它們。
int main(){
...
vector_type s, t;
...
vector_init_zeros(&s, dim);
vector_init_zeros(&t, dim);
vector_read(&s);
vector_read(&t);
}
要么
int main(){
...
vector_type *s, *t;
s = (vector_type *) malloc(sizeof(vector_type));
t = (vector_type *) malloc(sizeof(vector_type));
...
free(s);
free(t);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/431671.html
上一篇:更改后陣列未重新分配
