我有 2 个问题。
我想在 C 中创建一个文件数组。但我不确定是否必须在之前 malloc 大小。我可以只使用 FILE** 文件作为数组吗,还是必须在之前 malloc 它们。如果我必须腾出空间,我需要保留 4 个字节 (x86) 吗?
我有变量“char extra[8] = { 0xAE00AF00B000B100 };”我想将它分配给另一个 char 数组的末尾[24]。有没有一种更快的方法可以做到这一点,而不必手动输入每个值或使用 for 循环。
char extra[8] = { 0xAE00AF00B000B100 };
// index is a random place in the string
name[index] = '\0';
i = 0;
if (index > 16) {
for (i = 24-index; i < 8; i++) {
index++;
name[index] = extra[i];
}
}
else {
name[17] = 0xAE;
name[18] = 0x00;
name[19] = 0xAF;
name[20] = 0x00;
name[21] = 0xB0;
name[22] = 0x00;
name[23] = 0xB1;
name[24] = 0x00;
}
顺便说一句,我需要添加这些额外的字节。
最佳答案
I want to create an array of files in C. But I'm not sure whether I have to malloc the size before or not.Can I just use FILE** files as an array or do I have to malloc them before. And if I have to make space, do I need to reserve 4 bytes (x86)?
如果您需要一个文件数组,可以使用如下指针数组:
#include <stdio.h>
FILE *array[NB_FILES];
或者,如果 NB_FILES
仅在运行时已知,则可以动态执行此操作。
#include <stdio.h>
#include <stdlib.h>
FILE **array = malloc(nb_files * sizeof *array);
I have the variable "char extra[8] = { 0xAE00AF00B000B100 };" and I want to assign it to the end of another char array[24]. Is there a faster way of doing that without having to type in every value by hand or using a for loop.
标准 C 库提供了函数 memcpy
,它是许多编译器的内置函数(因此它比 for
循环更快)。
#include <string.h>
char array[24];
char extra[8];
memcpy(array + sizeof array - sizeof extra - 1, extra, sizeof extra);
关于c - 文件数组和赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14101259/