I'm a bit new to C here, and just wanted to understand a few things about pointers, pointers to pointers, and strings. Here's what I have written down so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Return a pointer to an array of two strings. The first is the characters
of string s that are at even indices and the second is the characters from
s that are at odd indices */
char **parity_strings(const char *s) {
int len = strlen(s);
char **lst = malloc(sizeof(char*)*2);
for(int i=0; i<2; i++){
lst[i] = malloc(sizeof(char)*(len/2));
}
for(int i=0; i<len; i++){
if(i%2==0){
(*lst)[0]=s[i];
}else{
(*lst)[1]=s[i];
}
}
return lst;
}
int main(int argc, char **argv) {
char **r = parity_strings(argv[1]);
printf("%s %s %s", r[0], r[1], argv[1]);
return 0;
}
So I want to dynamically allocate the memory needed for both the string array, and the strings themselves. I want to know if I have the right idea here by wanting to return a pointer of type char** which points to two pointers of type char*, and then from there access each char of the string.
My output is not as expected. I'm relatively new to C, so there are things I'm still learning about.
Any help would be appreciated, thanks.
lst[i] = malloc(sizeof(char)*(len/2));1) this will allocate too little if the string length happens to be odd 2) you also need space for the two'\0'terminators in the result strings. 2a) you need to null-terminate the resulting strings 3)(*lst)[0]=s[i];this is just wrong. What is your intention here?*(lst[0])=s[i]. I'm trying to access to the firstchararray