用户定义的数组元素和C中的数组大小 [英] User defined array elements and array size in C

查看:48
本文介绍了用户定义的数组元素和C中的数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C编程非常陌生,并且正在独自学习。我想编写一个代码,要求用户输入一些数字并将其存储到数组中。如果用户输入 q,程序将停止。然后应该打印该数组并告诉用户该数组中有多少个数字。 (长度)

I am very new to C programming and am learning on my own. I want to write a code that asks user to enter some numbers and store them into an array. The program would stop if the user enters 'q'. Then it is supposed to print the array and tell the user how many numbers are in that array. (the length)

我编写了以下代码,但是如果我将 int array []; 留空,则无法正常工作(显然)。我也无法定义它,因为它取决于用户输入的数字...我在Internet上进行了大量搜索,发现了malloc和calloc。我试图在这里使用它们,但老实说我不知道​​如何,现在我在这段代码上坐了几天。

I wrote the following code, but if I leave int array[]; empty, it does't work (obviously). I can't define it either because it depends on how many numbers the user enters... I searched a lot through the Internet and came across malloc and calloc. I tried to use them here but I honestly don't know how and I'm sitting on this code for a couple of days now.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int array[]; //I want to leave this empty but C doesn't allow me to.
int len=sizeof(array)/sizeof(array[0]);

for(int a=0;a<len;a++)
{
    printf("Enter element %d: ", a);
    scanf("%d",&array[a]);
    if(getchar()=='q')
        break;
}

printf("Array: [");
for(int a=0;a<len-1;a++)
{
    printf("%d, ", array[a]);
}   printf("%d]", array[len]);
printf("\nArray length: %d\n", len);
return 0;
}

int数组的样本输出[5];

Sample output for int array[5];

Enter element 0: 1
Enter element 1: 2
Enter element 2: 3
Enter element 3: 4
Enter element 4: 5
Array: [1, 2, 3, 4, 5]
Array length: 5

我们非常感谢您的帮助。

Any help is highly appreciated. Thanks and have a nice day.

推荐答案

Malloc和calloc函数允许您为变量动态分配内存。
我认为如果使用int指针( int * )代替 int [] 。
您可以执行以下操作

Malloc and calloc functions allows you to dynamically allocate memory for your variables. I think it would work better if you used an int pointer ( int* ) instead of int []. You can do something like this

int * array = malloc (sizeof(int)); //this will allocate enough memory for 1 int element
Len = 1;

然后在循环结束时,如果用户未输入 q,则可以做这样的事情

And then at the end of the loop, if the user doesn't enter 'q' you can do something like this

len ++ ;
array = realloc(array,len*sizeof(int)); //this will reallocate memory for your int pointer

重新分配内存,然后在代码末尾像这样调用free函数: free(array); 释放分配的内存。

Then at the end of the code you will have to call the function free like this : free(array); to free the allocated memory.

编辑: for循环将访问您不应该在 array [len] 中使用的内存。
我认为您应该将其更改为 array [len-1]

after the for loop you are accessing memory that you shouldn't in array[len]. I think you should change it to array[len-1]

这篇关于用户定义的数组元素和C中的数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆