-4

I am trying to access and manipulate a list of strings from a function in C but for some reason i get a seg fault as soon as the loop in the function does 1 pass.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void print_stuff(char*** what)
{
    for(int i = 0; i < sizeof(*what); ++i)
    {
        *what[i] = malloc(5 * sizeof(*what));
        *what[i] = "hello";
        printf("%s\n", *what[i]);
    }
}

int main(void)
{
    char** hello;
    hello = malloc(20 * sizeof(*hello));
    print_stuff(&hello);
}
  • 2
    This line: `*what[i] = "hello";` is probably not doing what you think it's doing. Research `strcpy`. – Chris Sep 15 '21 at 22:48
  • 4
    `sizeof(*what)` isn't the length of array, it's how many bytes a pointer variable requires (8 on 64-bit systems) – Jorengarenar Sep 15 '21 at 22:48
  • The answers to this question might be helpful: [Triple pointers in C: is it a matter of style?](https://stackoverflow.com/q/21488544/1679849) – r3mainer Sep 15 '21 at 22:53
  • 2
    There are rare occasions when you actually need `***` in C. This probably isn't one of them. Did you use `***` because you thought you needed it, or are you trying to get warnings to go away by inserting and deleting `*`'s? You should probably find a good book or tutorial and read about how pointers and arrays work. Also I suggest creating the array somewhere else, not inside a function called "`print_stuff`". – Steve Summit Sep 15 '21 at 23:37

1 Answers1

1

I was going to write a long, detailed answer, but it got too long considering the amount of problems I can think of about this code. So here is the short version. It looks like what you are trying to do can be done just like this.

#include <stdio.h>

int main(void)
{
    for(int i = 0; i < 20; i++) {
        printf("hello\n");
    }
}

I fail to understand the purpose of the rest of the code. It uselessly allocates memory, does not even do that correctly. And it's just wrong. Maybe more context is needed for what you are trying to achieve.

Abdelhakim AKODADI
  • 1,556
  • 14
  • 22
  • okay yeah cool thanks was just wondering. writing production code or anything like that. love stack overflow the community is so welcoming –  Mar 25 '22 at 04:22
  • @Jflee Your question was bad and no one could understand what you were trying to achieve. The skill of asking questions is something you learn, and no one born with it. Just get over it, and next time try with a clear goal. Refer to https://stackoverflow.com/help/how-to-ask for how to ask questions on SO, or maybe try reading other peoples' questions. – Abdelhakim AKODADI Mar 26 '22 at 13:04