Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 views
in Technique[技术] by (71.8m points)

c - Dynamic script with pointers

EDIT: I have the first part ready now, but I don't know how to make the last part where it says: Number 1 is 5 Number 2 is 5 Number 3 is 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
", 50);
    }

    printf("How much numbers would you like to enter?
");
    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]);
    } 
}
question from:https://stackoverflow.com/questions/65916187/dynamic-script-with-pointers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

there are a cople of problems in the code, I think the main issue is that when ever you want to scan an unknown amount of data, you have to dynamicly allocate memory. because you cant tell the computer exectly how much memory your program needs (while writing the code), you need to allocate memory during run-time of your program. to allocate the memory you can use malloc, which will allocate memory on the heap during run-time, for mor information about malloc.

(importent: when ever you use malloc you have to free the allocated data in order to avoid memory leacks).

a better way to implement this problem would be:

#include <stdio.h>
#include <malloc.h>

int main() {

int numbers;

//get the amount of numbers
printf("How much numbers would you like to enter?
");
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
", i+1);
    scanf("%d", &input[i]);
}
//print the numbers
for (int i = 0; i < numbers; ++i) {
    printf("Number %d is: %d
", i + 1, input[i]);
}
//free the memory to avoid memory leaks.
free(input);
}

hope it helps, if you have more quastions I would be happy to help, good luck! =)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...