Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

function - Adding the same number multiple times to an empty array in C

This is a piece of code to add the same number multiple times to an empty array but when I am printing the now non empty array, I am getting some other values:

#include<stdio.h>
#include<stdlib.h>


void sort_0(int arr[100], int i, int n){
    int final_array[100], c=0;

    // Count the number of '0' in the array
    for(i=0;i<n;i++){
        if(arr[i] == 0){
            c++;
        }
    }

    // Add the c number of '0' to the final_array
    for(i=0;i<c;i++){
        scanf("%d",final_array[i]);
    }

    for(i=0;i<c;i++){
        printf("%d ", final_array[i]);
    }
}
int main(){
    int arr[100], i, n;

    // Entering the size of the array
    scanf("%d", &n);

    // Entering n elements into the array
    for(i=0;i<n;i++){
        scanf("%d", &arr[i]);
    }

    sort_0(arr,i,n);
    
    return 0;
}

In the above code, the number of times 0 appears in the array is counted. Then the count is taken as the range and 0 is adding to the empty array final_array count times.

If c = 5, the final_array = {0,0,0,0,0}

Expected Output:

arr = {0,1,4,3,0}
Output = 2

I am not getting any output

question from:https://stackoverflow.com/questions/65540638/adding-the-same-number-multiple-times-to-an-empty-array-in-c

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

1 Reply

0 votes
by (71.8m points)

Since you don't know how much 0 you'll need to add to your array_final I figured out that a better solution could be to create that array after you have the number of 0 of the first array. Also, I see no reason why you were passsing i to the function since you can simply define it in the function itself.

void sort_0(int arr[10], int n, int* c){
        int i;
        for(i=0;i<n;i++){
            if(arr[i] == 0){
                (*c)+= 1;
            }
        }
}


int main (void) {
    int size;
    
    printf("Enter array size: ");
    scanf("%d", &size);
    int arr[size];
    for (int i=0;i<size;i++) {
        scanf("%d",&arr[i]);
    }
    
    int c = 0;
    sort_0(arr, size, &c);
    
    printf("C is: %d
",c);
    int* final_array;
    if ((final_array=malloc(c * sizeof(int)))==NULL) // should always check malloc errors
    { 
        perror("malloc");
        return -1;
    }
    for (int i=0;i<c;i++) {
        final_array[i]= 0;
    }
    
    printf("{");
    for (int i=0;i<c-1;i++) {
        printf("%d,", final_array[i]);
    }
    printf("%d}
",final_array[c-1]);
    
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...