简单得C语言问题!1

2025-03-31 00:08:29
推荐回答(3个)
回答1:

1、用指针:
可以用malloc(申请空间)和realloc(重新申请空间)可以改变指针所指空间大小。程序事例如下:

#include
#include
#include

int main(void)
{
char *str;

/* allocate memory for string */
str = malloc(10);

/* copy "Hello" into string */
strcpy(str, "Hello");

printf("String is %s\n Address is %p\n", str, str);
str = realloc(str, 20);
printf("String is %s\n New address is %p\n", str, str);

/* free memory */
free(str);

return 0;
}

2、在C++ 中,可以用STL的向量:vector

回答2:

去掉N的宏定义

在主函数声明部分加入:
int N;
scanf("%d",&n);
float* a = (float*) malloc ( N * sizeof(float) );
或者C++风格的:
int N;
cin>>N;
float* a = new float(n);

回答3:

据我所知,c中的数组是必须规定大小的,不过字符数组例外,如果想要使用任意长度的数组的话,可以使用链表