[英]How to set a char 'a' to a char pointer array?
I'm trying to figure out how to use pointers. 我试图弄清楚如何使用指针。
I'm confused on how to insert an individual char to the char *line2[80] 我对如何在char * line2 [80]中插入单个char感到困惑
Is this even possible to do this without referencing the memory location of another pointer? 甚至可以在不引用另一个指针的存储位置的情况下做到这一点?
My thought process is that at *line2[0] = 'a' the character 'a' will be at index 0 of the array. 我的想法是,在* line2 [0] ='a'处,字符'a'将在数组的索引0处。
How is this different from line[0] = 'a' 这与line [0] ='a'有何不同?
#include <stdio.h>
void returnValue(void);
int main(void){
returnValue();
}
void returnValue(){
char line[80];
line[0] = 'a';
line[1] = '\0';
printf("%s",line);
char* line2[80];
*line2[0] = 'a';
*line2[1] = '\0';
printf("%s",*line2); //program crashes
}
When you allocate 分配时
char* line2[80];
You are allocating an array of 80 character pointers . 您正在分配80个字符指针的数组 。
When you use 使用时
*line2[0] = 'a';
You are referencing undefined behaviour. 您正在引用未定义的行为。 This is because you are allocating the pointer
line2[0]
, but the pointer is not initialized and may not be pointing to any valid location in memory. 这是因为您正在分配指针
line2[0]
,但是指针未初始化,并且可能未指向内存中的任何有效位置。
You need to initialize the pointer to some valid location in memory for this to work. 您需要将指针初始化为内存中某个有效位置的指针才能起作用。 The typical way to do this would be to use
malloc
典型的方法是使用
malloc
line2[0] = malloc(10); // Here 10 is the maximum size of the string you want to store
*line2[0] = 'a';
*(line2[0]+1) = '\0';
printf("%s",*line2);
What you are doing in the above program is allocating a 2D array of C strings. 您在上述程序中所做的是分配一个C字符串的2D数组。
line2[0]
is the 1st string. line2[0]
是第一个字符串。 Likewise, you can have 79 more strings allocated. 同样,您可以再分配79个字符串。
you must have already read, a pointer is a special variable in c
which stores address of another variable of same datatype
. 您必须已经读过,指针是
c
一个特殊变量,它存储相同datatype
的另一个变量的地址。
for eg:- 例如:
char a_character_var = 'M';
char * a_character_pointer = &a_character_var; //here `*` signifies `a_character_pointer` is a `pointer` to `char datatype` i.e. it can store an address of a `char`acter variable
likewise in your example 同样在您的示例中
char* line2[80];
is an array of 80
char
pointer 是
80
char
指针的数组
usage 用法
line2[0] = &line[0];
and you may access it by writing *line2[0]
which will yield a
as output 您可以通过编写
*line2[0]
来访问它,这将产生a
输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.