C - Storing Array Data | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

C - Storing Array Data

I have a function that is supposed to create an array of character arrays (char**). I can point a single char* to char**[k] and print the result just fine. However, when iterating over char** to list each contained char*, the result that was printed properly does not convert over to the char** elements, and instead prints 0. My "NUMBERS SEGMENT" and "LETTERS SEGMENT" print functions display the desired result. Issue is further explained in code comments: https://code.sololearn.com/c0PaLrLE1407/#c

4th Jan 2020, 9:01 AM
NULL
NULL - avatar
3 Answers
+ 1
Aaron Eberhardt Coder Kitten Thanks guys! About the type casting thing: I posted this on another forum and was told to remove the type casting on char since it’s technically redundant, but I do also prefer to to keep it for clarity, I can see both sides of that :) And I appreciate the mini lesson on pointers, I’m still figuring it out and the explanation helps a ton!
4th Jan 2020, 7:11 PM
NULL
NULL - avatar
0
I think the error might be caused by a misunderstanding of how to use pointers correctly. Let's have a look at those three lines: char *numbers = malloc(MAX_INPUT); char *character = malloc(4); char** segment_array = malloc(MAX_INPUT*MAX_INPUT); 1. It's bad to use malloc without multiplying with sizeof() even if you know that sizeof(char) is one. There might be cases where similar assumptions are wrong. 2. Usually you type cast malloc pointers because malloc returns void pointers. Therefore you'd write char* numbers = (char*)malloc(MAX_INPUT*sizeof(char)); to avoid warnings and errors. 3. The third line is as far I understand it wrong. If you want to have a maximum of MAX_INPUT (heap allocated) arrays you just need 32 (MAX_INPUT) pointers to them. Therefore the third line should look like this: char** segment_array = (char**) malloc(MAX_INPUT*sizeof(char*)); 4. If you want to use up to MAX_INPUT arrays you also need to allocate them somewhere. You can't just simply allocate "numbers" once and use it 32 times.
4th Jan 2020, 9:38 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
0
Coder Kitten sometimes you need to typecast though otherwise you may discard qualifiers like volatile. And you also lower the risk of accidentally breaking your code by changing a datatype of a struct for example: If you type cast the compiler will always warn if you don't it's up to you to find all affected sections of the code. For me it seems like most unexperienced C devs tend to be implicit while experienced devs are more explicit which also includes type casting.
4th Jan 2020, 10:11 AM
Aaron Eberhardt
Aaron Eberhardt - avatar