带指针的动态脚本
Dynamic script with pointers
编辑:我现在已经准备好了第一部分,但我不知道如何制作最后一部分:
数字 1 是 5
数字 2 是 5
数字 3 是 5
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int amount;
int *p_array;
int i;
int j;
p_array = (int *)malloc(sizeof(int)*50);
if(p_array == NULL) {
printf("malloc of size %d failed\n", 50);
}
printf("How much numbers would you like to enter?\n");
scanf("%d", &amount);
for(int i = 1; i <= amount; ++i) {
printf("number %d: ", i);
scanf("%d", &p_array[1]);
}
for(int j = 0; j <= amount; ++j) {
printf("%d", p_array[i]);
}
}
您需要声明一个可以容纳数字的数组:
scanf("%d", &numbers);
int a[numbers];
接下来可以用指针访问数组:
int *pa= a;
for (i = 0; i < numbers; i++) {
scanf("%d", pa);
pa++;
}
代码中有很多问题,我认为主要问题是当你想扫描未知数量的数据时,你必须动态分配内存。因为您不能准确地告诉计算机您的程序需要多少内存(在编写代码时),所以您需要在程序的 运行 时间内分配内存。
要分配内存,您可以使用 malloc,它将在 运行-time for mor information about malloc.
期间在堆上分配内存
(重要:当你使用 malloc 时,你必须释放分配的数据以避免内存泄漏)。
解决这个问题的更好方法是:
#include <stdio.h>
#include <malloc.h>
int main() {
int numbers;
//get the amount of numbers
printf("How much numbers would you like to enter?\n");
scanf("%i", &numbers);
//allocate memory(on the heap) for the numbers
int* input = (int*) malloc (sizeof(int)*numbers);
//get the numbers
for (int i = 0; i < numbers; ++i) {
printf("Number %d\n", i+1);
scanf("%d", &input[i]);
}
//print the numbers
for (int i = 0; i < numbers; ++i) {
printf("Number %d is: %d\n", i + 1, input[i]);
}
//free the memory to avoid memory leaks.
free(input);
}
希望对您有所帮助,如果您有更多问题,我很乐意提供帮助,
祝你好运! =)
编辑:我现在已经准备好了第一部分,但我不知道如何制作最后一部分: 数字 1 是 5 数字 2 是 5 数字 3 是 5
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int amount;
int *p_array;
int i;
int j;
p_array = (int *)malloc(sizeof(int)*50);
if(p_array == NULL) {
printf("malloc of size %d failed\n", 50);
}
printf("How much numbers would you like to enter?\n");
scanf("%d", &amount);
for(int i = 1; i <= amount; ++i) {
printf("number %d: ", i);
scanf("%d", &p_array[1]);
}
for(int j = 0; j <= amount; ++j) {
printf("%d", p_array[i]);
}
}
您需要声明一个可以容纳数字的数组:
scanf("%d", &numbers);
int a[numbers];
接下来可以用指针访问数组:
int *pa= a;
for (i = 0; i < numbers; i++) {
scanf("%d", pa);
pa++;
}
代码中有很多问题,我认为主要问题是当你想扫描未知数量的数据时,你必须动态分配内存。因为您不能准确地告诉计算机您的程序需要多少内存(在编写代码时),所以您需要在程序的 运行 时间内分配内存。 要分配内存,您可以使用 malloc,它将在 运行-time for mor information about malloc.
期间在堆上分配内存(重要:当你使用 malloc 时,你必须释放分配的数据以避免内存泄漏)。
解决这个问题的更好方法是:
#include <stdio.h>
#include <malloc.h>
int main() {
int numbers;
//get the amount of numbers
printf("How much numbers would you like to enter?\n");
scanf("%i", &numbers);
//allocate memory(on the heap) for the numbers
int* input = (int*) malloc (sizeof(int)*numbers);
//get the numbers
for (int i = 0; i < numbers; ++i) {
printf("Number %d\n", i+1);
scanf("%d", &input[i]);
}
//print the numbers
for (int i = 0; i < numbers; ++i) {
printf("Number %d is: %d\n", i + 1, input[i]);
}
//free the memory to avoid memory leaks.
free(input);
}
希望对您有所帮助,如果您有更多问题,我很乐意提供帮助, 祝你好运! =)