[英]How do I use malloc() to allocate memory to store an array of strings?
I am trying to create a program that populates a fixed-size argument array using the arguments passed through the terminal. 我正在尝试创建一个程序,该程序使用通过终端传递的参数来填充固定大小的参数数组。 My first step is trying to create and populate the array of default argument strings, which I have succeeded in doing.
我的第一步是尝试创建并填充默认参数字符串数组,这是我成功完成的。 However, I am now trying to use
malloc()
to allocate space for this array, and cannot get it to compile. 但是,我现在尝试使用
malloc()
为该数组分配空间,并且无法对其进行编译。 I've tried everything I can think of regarding the proper syntax. 关于正确的语法,我已经尝试了所有可以想到的方法。 I've tried doing more research into
malloc()
and how to use it for two dimensional arrays, but I haven't found any information that helps me. 我已经尝试对
malloc()
以及如何将其用于二维数组进行更多研究,但是我没有找到任何对我有帮助的信息。 I'm stuck and not sure what to do next. 我被卡住了,不确定下一步该怎么做。 Here is the code:
这是代码:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define MAX_NUM_OF_ARGS 5
#define MAX_ARG_SIZE 256
int main(int argc, char **argv) {
printf("%s%d\n", "Length: ", argc); //for debug purposes
// Make sure we don't have more than five arguments
if(argc > MAX_NUM_OF_ARGS) {
printf("%s", "Too many arguments. Must enter fewer than 4.");
}
// Populate the array
else{
char defaultArgs[] = "defaultArgs"; //create default argument array
//allocate memory for default array
char argumentArray[MAX_NUM_OF_ARGS][MAX_ARG_SIZE] =
(char *)malloc(MAX_NUM_OF_ARGS * MAX_ARG_SIZE * sizeof(char));
//populate array with default arguments
for (int i = 0; i < MAX_NUM_OF_ARGS; i++) {
strcpy(argumentArray[i], defaultArgs);
printf("%s\n", argumentArray[i]);
}
free(argumentArray);
return 0;
}
}
When I try to compile I get an invalid initializer error at the ( char*
) cast for malloc()
. 当我尝试编译时,在对
malloc()
进行( char*
)转换时收到无效的初始化错误。 I've tried casting it to ( char**
) and ( char
) and also changing the sizeof(char)
to sizeof(char*)
and sizeof(char**)
. 我试过将其强制转换为(
char**
)和( char
),还将sizeof(char)
更改为sizeof(char*)
和sizeof(char**)
。
I am not really sure what I am doing wrong at this point and I am at a loss as far as what to even try next. 我现在不确定自己在做什么错,而且我甚至不知道下一步该怎么做。
You've declared argumentArray
as a two-dimensional array of char
. 您已将
argumentArray
声明为char
的二维数组。 The malloc
function returns a pointer, so you can't assign a pointer to an element of this array. malloc
函数返回一个指针,因此您不能将指针分配给该数组的元素。
You need a pointer to store what's being returned. 您需要一个指针来存储返回的内容。 Actually, in this case you need a pointer to a pointer, and you'll need to call
malloc
multiple times, once for an array of pointers for the arguments, then again in a loop for each argument: 实际上,在这种情况下,您需要一个指向指针的指针,并且需要多次调用
malloc
,一次调用参数的指针数组,然后再次循环每个参数:
char **argumentArray = malloc(MAX_NUM_OF_ARGS * sizeof(char *));
for (int i=0; i<MAX_NUM_OF_ARGS; i++) {
argumentArray[i] = malloc(MAX_ARG_SIZE);
strcpy(argumentArray[i], defaultArgs);
printf("%s\n", argumentArray[i]);
}
You cannot store an array of strings in C, as a string is a variable-length datastructure, not a simple type. 您不能在C中存储字符串数组,因为字符串是可变长度数据结构,而不是简单类型。
So, decide what you want: 因此,决定您想要什么:
An array of fixed-length buffers storing strings of fixed (maximum) length. 固定长度缓冲区的数组,用于存储固定(最大)长度的字符串。
char (*p)[MAX_LEN] = malloc(n * sizeof *p); // Store the strings at p[0], p[1], …, p[n - 1]
A buffer storing any number of strings consecutively. 一个连续存储任意数量字符串的缓冲区。
char* p = malloc(sum_of_string_lengths + count_of_strings); // Now fill in the strings one after the other, including Terminator
An array of pointers to strings. 指向字符串的指针数组。
char** p = malloc(n * sizeof *p); p[0] = strdup(source[0]); // ... // p[n - 1] = ...
With strdup()
the common utility-function defined like: 使用
strdup()
定义的通用实用程序功能如下:
char* strdup(const char* s) { size_t n = strlen(s) + 1; char* r = malloc(n); if (r) memcpy(r, s, n); return r; }
Try thinking about it like this: 尝试这样思考:
Here is an example where I make an array of char *. 这是我制作char *数组的示例。 Essentially the pointer returned by malloc points to an area where char * will reside.
本质上,malloc返回的指针指向char *将驻留的区域。 Here is an illustration of what is going on.
这是正在发生的情况的说明。
/*
malloc_ret_ptr ---> [ char * my_str1 | char * my_str2 | char * my_str3 ]
| | |
| | |
v v v
"Thank" "You" "Chicago"
*/
int main() {
char * my_string = "this is my string";
char ** my_string_array;
my_string_array = malloc(sizeof(char*)*10); //Create an array of character pointers
//Place char * inside of char * array
my_string_array[0] = my_string;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.