如何在c中创建动态数组? [英] How do I create dynamic arrays in c?

查看:118
本文介绍了如何在c中创建动态数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我在c中创建一个程序,我想使用动态指针。问题是以下....



我有一个只包含两行数字的txt文件。在第一行中只有一个数字表示数组必须有多大以及数字应该保持多少。

在第二行中,第一行的数字与第一行一样多。

-----------------

例如。 file.txt 
9
982 82 89418 929 98 419925 98 41280 9841



-------------

如你所见第一行说我们要存储 9 数字,在第二行我们有 9 我们应该存储的数字。



问题是 9 的数字可以来自 1 250.000 我无法创建存储这么多数字的代码。



如何在动态指针数组中存储 250.000 数字。当然,当我存储数字时,我需要为每个数字设置不同的地址,因此在我的代码的下一部分中,我可以拨打任何我想要的号码。我怎么想这样做?



我读过以下课程,但我无法理解我是怎么想的。

http://www.programiz.com/c-programming/c-dynamic-memory-分配 [ ^ ]

解决方案



  1. 读取第一行并将其转换为整数。
  2. 使用 malloc 创建指向整数数组的指针。数组长度是从首次读取的数字设置的。
  3. 一次从文本文件中读取剩余的字段。
  4. 使用 strtok 将每一行拆分为多个项目。
  5. 将每个项目转换为整数并存储在数组的下一个空闲元素中。
  6. 重复直到所有项目都已处理完毕。



所有函数的文档( malloc strtok 等)可以在 http://msdn.microsoft.com/en-us/library/找到634ca0c2.aspx [ ^ ]


Hello guys,
I create a program in c and I want to use dynamic pointers. The problem is the following....

I have a txt file that contains only two lines of numbers. In the first line there is only one number that says how big must be the array and how many numbers should hold.
In the second line there are as many numbers as the first line say.
-----------------

Eg. file.txt 
9 
982 82 89418 929 98 419925 98 41280 9841 


-------------
As you see the first line says that we want to store 9 numbers and in the second line we have the 9 numbers we should store.

The problem is that the number 9 can be from 1 to 250.000 which I can't create a code to store so many numbers.

How can I store until 250.000 numbers in an dynamic array of pointers. Of course when I'll store the numbers i need a different address for each number so in the next part of my code i could call any number i want. How am I suppose to do that?

I read the following courses, but I couldn't understand how am I suppose to do it.
http://www.programiz.com/c-programming/c-dynamic-memory-allocation[^]

解决方案


  1. Read the first line and convert it to an integer.
  2. Use malloc to create a pointer to an array of integers. The array length is set from the number first read.
  3. Read the remaining fields from the text file one line at a time.
  4. Use strtok to split each line into items.
  5. Convert each item to an integer and store in the next free element of the array.
  6. Repeat until all items have been processed.


The documentation for all functions (malloc, strtok etc.) can be found at http://msdn.microsoft.com/en-us/library/634ca0c2.aspx[^].


这篇关于如何在c中创建动态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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