输出为0的动态内存分配问题
dynamic memory allocation problem with 0 as output
我正在尝试使用 malloc
创建动态内存分配,但我总是得到 0 作为输出而不是 5。
我的代码
typedef struct{
int nl;
double *vect;
}vect_t;
void creerVecteur(vect_t *ptrVect){
double *p;
ptrVect->vect=(double *)malloc(ptrVect->nl*sizeof(double));
ptrVect->vect[0] = 5;
ptrVect->vect[1] = 7;
ptrVect->vect[2] = 2;
printf("%d\n",ptrVect->vect[0]);
}
int main(){
vect_t v1;
v1.nl = 3;
creerVecteur(&v1);
}
您对 printf
使用了错误的格式说明符。
%d
格式说明符用于以十进制格式打印 int
。要打印 double
,请使用 %f
.
只需使用%g
或%f
将double
浮点类型指定为printf()
。你是在告诉 printf()
你要通过 int
和 %d
。
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int nl;
double *vect;
} vect_t;
void creerVecteur(vect_t *ptrVect)
{
double *p;
ptrVect->vect=(double *)malloc(ptrVect->nl * sizeof(double));
ptrVect->vect[0] = 5;
ptrVect->vect[1] = 7;
ptrVect->vect[2] = 2;
printf("%g\n",ptrVect->vect[0]);
}
int main()
{
vect_t v1;
v1.nl = 3;
creerVecteur(&v1);
}
输出:
$ a.out
5
$ _
我正在尝试使用 malloc
创建动态内存分配,但我总是得到 0 作为输出而不是 5。
我的代码
typedef struct{
int nl;
double *vect;
}vect_t;
void creerVecteur(vect_t *ptrVect){
double *p;
ptrVect->vect=(double *)malloc(ptrVect->nl*sizeof(double));
ptrVect->vect[0] = 5;
ptrVect->vect[1] = 7;
ptrVect->vect[2] = 2;
printf("%d\n",ptrVect->vect[0]);
}
int main(){
vect_t v1;
v1.nl = 3;
creerVecteur(&v1);
}
您对 printf
使用了错误的格式说明符。
%d
格式说明符用于以十进制格式打印 int
。要打印 double
,请使用 %f
.
只需使用%g
或%f
将double
浮点类型指定为printf()
。你是在告诉 printf()
你要通过 int
和 %d
。
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int nl;
double *vect;
} vect_t;
void creerVecteur(vect_t *ptrVect)
{
double *p;
ptrVect->vect=(double *)malloc(ptrVect->nl * sizeof(double));
ptrVect->vect[0] = 5;
ptrVect->vect[1] = 7;
ptrVect->vect[2] = 2;
printf("%g\n",ptrVect->vect[0]);
}
int main()
{
vect_t v1;
v1.nl = 3;
creerVecteur(&v1);
}
输出:
$ a.out
5
$ _