C - 构建动态分配的指针数组,指向填充了文件输入的结构(C - Build dynamically allocated array of pointers to structures filled with input from file)

我需要构建一个指向动态分配结构(DBrecord)的指针数组,并用另一个文件的输入填充该数组。 不知道如何处理这个问题。

数据文件将首先具有条目数,然后是特定顺序的条目。

numOfEntries

lastName firstName studentID year gpa expGradYear

例:

1

Doe John 12345678 senior 3.14159 2015

这是我到目前为止的代码:

class.h

typedef enum {firstYear, sophomore, junior, senior, grad} class;

main.c中

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

int main(){

//DBrecord is name for structure
struct DBrecord{
int DBrecordID;     //ID for each entry, range 0-319
char *last;         //student last name
char *first;        //student first name
char studentID[8];  //student ID
int age;            //student age
class year;         //year in school
float gpa;          //GPA
int expGradYear;    //expected graduation year
};
int numEntries;     //total number of entries, first num in data file
struct DBrecord **ptrToDB;

//scan first int in data file and assign to numEntries
scanf("%d", &numEntries);

//allocate memory for structures, each is 36 bytes
*ptrToDB = malloc (sizeof(struct DBrecord) * numEntries);

//free allocated memory
free(ptrToDB);

//build an array of pointers to dynamically allocated structures
//fill that array with input from data file

//build 7 arrays of pointers to DBrecords, one for each field except DB ID
//sort each a different way
//note the 7 arrays are pointers, no copying

//print each of the 7 sorted arrays

return 0;
}

I need to build an array of pointers to dynamically allocated structures (DBrecord) and fill that array with input from another file. Not sure how to approach this.

The data file will have the number of entries first, followed by entries in a specific order.

numOfEntries

lastName firstName studentID year gpa expGradYear

example:

1

Doe John 12345678 senior 3.14159 2015

Here's the code I have so far:

class.h

typedef enum {firstYear, sophomore, junior, senior, grad} class;

main.c

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

int main(){

//DBrecord is name for structure
struct DBrecord{
int DBrecordID;     //ID for each entry, range 0-319
char *last;         //student last name
char *first;        //student first name
char studentID[8];  //student ID
int age;            //student age
class year;         //year in school
float gpa;          //GPA
int expGradYear;    //expected graduation year
};
int numEntries;     //total number of entries, first num in data file
struct DBrecord **ptrToDB;

//scan first int in data file and assign to numEntries
scanf("%d", &numEntries);

//allocate memory for structures, each is 36 bytes
*ptrToDB = malloc (sizeof(struct DBrecord) * numEntries);

//free allocated memory
free(ptrToDB);

//build an array of pointers to dynamically allocated structures
//fill that array with input from data file

//build 7 arrays of pointers to DBrecords, one for each field except DB ID
//sort each a different way
//note the 7 arrays are pointers, no copying

//print each of the 7 sorted arrays

return 0;
}

原文:https://stackoverflow.com/questions/10076261
2023-11-23 10:11

满意答案

当你有多个链接在一起的elsif / elsif块时,只有其中一个会运行,并且第一个具有真实条件的块将被运行。 所以,块的顺序很重要。 例如:

if true
  puts 'this code will run'
elsif true
  puts 'this code will not run'
end

即使这些块的条件都是真的,只有第一个运行。 如果你想让两者都运行,使用两个独立的if块,如下所示:

if true
  puts 'this code will run'
end

if true
  puts 'this code will also run'
end

When you have multiple if/elsif blocks chained together, only one of them will run, and the first block to have a true condition will be the one to be run. So, the order of the blocks matters. For example:

if true
  puts 'this code will run'
elsif true
  puts 'this code will not run'
end

Even though the conditions for those blocks are both true, only the first one is run. If you want to have both run, use two separate if blocks, like this:

if true
  puts 'this code will run'
end

if true
  puts 'this code will also run'
end

相关问答

更多

更改烧瓶中的URL路由会破坏代码吗?(Would changing URL route in flask break the code?)

不,因为url_for采用函数的名称,而不是url。 所以如果你的功能是: # ...Code, imports... @app.route('/cvolume/') def volume(): return 'Hello world!' @app.route('/volume/') def volume_2(): return 'Hello You!' @app.route('/test/') def test(): return redirect(url_for('...

python:在几个条件之后没有定义变量(python: variable not getting defined after several conditionals)

如果CACHE_LIST_1是一个空序列,那么switch永远不会被绑定。 If CACHE_LIST_1 is an empty sequence then switch will never get bound.

具有多个条件的if的执行顺序(Order of execution for an if with multiple conditionals)

这种评估叫做短路 。 一旦结果是100%清楚,它不会继续评估。 这实际上是一种常见的编程技术。 例如,在C ++中,你会经常看到: if (pX!=null && pX->predicate()) { bla bla bla } 如果您更改了条件的顺序,则可以调用空指针和崩溃方法。 当有一个指向该结构体的指针时,C中类似的示例将使用结构体的字段。 你可以做类似的事情: if(px==null || pX->isEmpty()} { bla bla bla } 这也是在if条件下避免副作用通常是...

我怎么推理Coq的条件?(How do I reason about conditionals in Coq?)

你试过这个吗? (语法可能有问题,在这里没有coqtop) destruct (Aeq_dec x a); [ subst; elim (n eq_refl) | right; apply (IHxs H) ]. ( if <foo>与match <foo> with或多或少相同。你必须减少( destruct , case ,...)以便可以决定匹配(或者if , if必须减少到你使用它的任何类型的第一个或第二个构造函数。)大多数时候,你需要得到案例分析的值(虽然不在这里)。如果你需要它,做一...

为什么改变条件的顺序会破坏我的代码?(Why does changing the order of conditionals break my code?)

当你有多个链接在一起的elsif / elsif块时,只有其中一个会运行,并且第一个具有真实条件的块将被运行。 所以,块的顺序很重要。 例如: if true puts 'this code will run' elsif true puts 'this code will not run' end 即使这些块的条件都是真的,只有第一个运行。 如果你想让两者都运行,使用两个独立的if块,如下所示: if true puts 'this code will run' end if t...

重构条件(Refactoring conditionals)

这是状态模式有助于管理代码复杂性的完美示例,特别是如果您将来添加其他LicensingOption和CalcTypes。 这种模式在计算机编程中用于根据其内部状态封装同一对象的不同行为。 对于对象来说,这可以是一种更简洁的方式,可以在运行时更改其行为,而无需使用大型单片条件语句,从而提高可维护性。 我在下面附上了一个关于你的案例的State模式实现的例子,但是请注意,你的代码示例很难真正给你很好的建议( printW1 , printHeaderZ和printHeaderA并没有给我那么多信息关于...

PHP If / Else Multiple Conditionals(PHP If/Else Multiple Conditionals)

您可以使用isset作为语言构造而不是函数调用: if(isset($_POST['cool']) && $_POST['cool'] == 1) You can use isset which is a language construct as opposed to a function call: if(isset($_POST['cool']) && $_POST['cool'] == 1)

如何正确使用logstash条件(if ... in)?(How to use logstash conditionals(if…in) correctly?)

正如你所说的,将"[geoip][timezone]" => "unknown"添加到所有事件中。 这意味着if !([timezone] in [geoip]) 。 我想这个检查字段timezone (不是geoip.timezone )是否与字段geoip具有相同的值。 因此[timezone] in [geoip]测试中的[timezone] in [geoip]始终评估为false,因此所有事件都会得到"[geoip][timezone]" => "unknown" 。 要测试一个字段是否...

吞咽的条件(Conditionals in gulp)

您可以使用lazypipe进行minify和rename变换。 它会是这样的: var minifyAndRenameCSS = lazypipe() .pipe(minifyCSS({keepSpecialComments:0}) .pipe(rename({suffix: '.min'})); gulp.task('build', function() { return gulp.src('*.css') .pipe(gulpif(env === 'production'...

以下条件是否相同(Are the following conditionals equivalent)

更简单,你可以分解出常见的部分: if array[i][j] == 1 and (IterateAPP == 1 or (i,j) not in APP): # do stuff 你有很好的变量名称约定:) Even simpler, you can factor out the common part: if array[i][j] == 1 and (IterateAPP == 1 or (i,j) not in APP): # do stuff Curious vari...

相关文章

更多

zoj 2966 Build The Electric System

ZOJ Problem Set - 2966 Build The Electric Sys ...

Nutch 1-build

1. install software Cygwin, jdk, ant, nutch 2. conf ...

My W3C Custom Mapping File

[hdhw] HotKey=W Tip=Train Dragonha|cffffcc00w|r ...

redhat6.4上build storm 0.9.0.1

1.安装mvn 2.下载源代码 3.build mvn package 过程中出现问题,clojars ...

【Hadoop】Build and Run HDFS

今天再一次配置HDFS,决定记录下来以备不时之需。 首先你的电脑需要安装上java JDK 1.6 这 ...

重新Build Hadoop后进入Hive客户端异常

在自己虚拟机上使用mysql作为hive元数据存储, 修改配置如下: &lt;pro ...

用‘button’跟‘text’组合代替‘file’,选择文件后点‘submit’,‘file’的值被清空

各位大虾晚上好,我有个问题想请教你们,我想美化html的file外观,但貌似现在还不能用css直接设计 ...

《数据结构与STL》(Data Structures and the Standard Template Library)扫描版[PDF]

中文名: 数据结构与STL 原名: Data Structures and the Standa ...

Java 流(Stream)、文件(File)和IO

Java 流(Stream)、文件(File)和IO Java.io包几乎包含了所有操作输入、输 ...

shell 脚本执行,出现错误bad interpreter: No such file or directory

出现bad interpreter:No such file or directory的原因 是文件格 ...

最新问答

更多

您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)

将diff文件复制到存储库的根目录,然后执行以下操作: git apply yourcoworkers.diff 有关apply命令的更多信息, apply 见其手册页 。 顺便说一下:一个更好的方法是通过文件交换整个提交文件是发送者上的命令git format-patch ,然后在接收器上加上git am ,因为它也传送作者信息和提交信息。 如果修补程序应用程序失败,并且生成diff的提交实际上在您的备份中,则可以使用尝试在更改中合并的apply程序的-3选项。 它还适用于Unix管道,如下

将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)

尝试将第二行更改为snprintf(buf1, sizeof buf1, "%.2f", balance1); 。 另外,为什么要声明用该特定表达式分配缓冲区的存储量? EDIT @LưuVĩnhPhúc在下面的评论中提到我的原始答案中的格式说明符将舍入而不是截断,因此根据如何在不使用C舍入的情况下截断小数,您可以执行以下操作: float balance = 200.56866; int tmp = balance1 * 100; float balance1 = tmp / 100.0; c

OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)

这是简单的解决方案 在你需要写的控制器中 BackendMenu::setContext('Archetypics.Team', 'website', 'team'); 请参阅https://octobercms.com/docs/backend/controllers-views-ajax#navigation-context BackendMenu::setContext('Author.Plugin name', 'Menu code', 'Sub menu code'); 你需要在r

页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)

每当发出请求时ASP都会创建一个新的Page对象,并且一旦它将响应发送回用户就不会保留对该Page对象的引用,因此只要你找不到某种方法来保持生命自己引用该Page对象后,一旦发送响应, Page和只能通过该页面访问的所有对象才有资格进行垃圾回收。 ASP creates a new Page object whenever a request is made, and it does not hold onto the reference to that Page object once it

codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)

要在生产服务器中调试这个,你可以临时放 error_reporting(E_ALL); 并查看有哪些其他错误阻止正确的重定向。 您还应该检查生产服务器发送的响应标头。 它是否具有“缓存”,是否需要重新验证标头等 to debug this in production server, you can temporary put error_reporting(E_ALL); and see what other errors are there that prevents the proper

在计算机拍照在哪里进入

打开娥的电脑.在下面找到视频设备点击进去就可以了...

使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)

你是对的。 第一次输入后,换行符将保留在输入缓冲区中。 第一次读取后尝试插入: cin.ignore(); // to ignore the newline character 或者更好的是: //discards all input in the standard input stream up to and including the first newline. cin.ignore(numeric_limits::max(), '\n'); 您必须为#inc

No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)

for (int k = 0; k > 10; k++) { System.out.println(k); } k不大于10,所以循环将永远不会执行。 我想要什么是k<10 ,不是吗? for (int k = 0; k < 10; k++) { System.out.println(k); } for (int k = 0; k > 10; k++) { System.out.println(k); } k is not greater than 10, so loop

单页应用程序:页面重新加载(Single Page Application: page reload)

优点是不注销会避免惹恼用户,以至于他们会想要杀死你:-)。 说真的,如果每次刷新页面时应用程序都会将我注销(或者在新选项卡中打开一个链接),我再也不会使用该应用程序了。 好吧,不要这样做。 确保身份验证令牌存储在刷新后的某个位置,即不在某些JS变量中,而是存储在cookie或本地存储中。 The advantage is that not logging off will avoid pissing off your users so much that they'll want to kill

在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)

EXECUTE IMMEDIATE 'SELECT '||field_val_temp ||' FROM tableb WHERE function_id = :func_val AND rec_key = :rec_key' INTO field_val USING 'STDCUSAC' , yu.rec_key; 和, EXECUTE IMMEDIATE 'UPDATE tablec SET field_val_'||i||' = :field_val' USI