简体   繁体   中英

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]

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.

How is this different from 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 .

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.

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

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. line2[0] is the 1st string. Likewise, you can have 79 more strings allocated.

you must have already read, a pointer is a special variable in c which stores address of another variable of same 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

usage

line2[0] = &line[0];

and you may access it by writing *line2[0] which will yield a as output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM