0

C- language——-Trying to call a function "test" from main(). This takes 3 arguments argc, argv and a pointer function which either turns the string into lower case or upper case. Then using the array of modified values i will just loop and print them.

I get segmentation fault error.
I want to return the entire array. So that in my main() i will loop through it and print it. How can i do this? Where am i going wrong in my code? Any help would be great.

Redman
  • 19
  • 6
  • Is this code intended to be compiled with a C compiler or a C++ compiler? If the latter, there are *much* better ways to return an array of strings than via `malloc()`. – Jeremy Friesner Sep 24 '21 at 03:31
  • You should step through with your debugger and find out where the seg fault occurs, and verify that different allocated memories are what you expect. I'm removing the C++ tag unless someone sees any specific thing in the code that is C++ specific. – JohnFilleau Sep 24 '21 at 03:32
  • Its in C language. – Redman Sep 24 '21 at 03:36

2 Answers2

1

Your codes have some incorrect points and are redundant as well. You can try the below codes

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

char **test(int argc, const char *const *argv, int (*const chnge)(int)){

    char **retArr = malloc((argc+1) * sizeof(char*));

    for (int i = 0; i < argc; ++i) {

        const char *str = argv[i];
        int len = strlen(str);

        char* transform = malloc((len+1) * sizeof(char));

        for (int j = 0; j < (len+1); ++j) {
            transform[j] = chnge(str[j]);
        }
        retArr[i] = transform;
   }
   retArr[argc] = NULL; // An array of char* terminated by NULL
   return retArr;
}


int main(int argc, const char *const *argv) {

  char **val1 = test(argc, argv, &toupper);
  char **val2 = test(argc, argv, &tolower);

  for (char *const *p = val1, *const *q = val2; *p && *q; ++argv, ++p, ++q) {
    printf("[%s] -> [%s] [%s]\n", *argv, *p, *q);
    free(*p);
    free(*q);
  }
  free(val1);
  free(val2);
}
nhatnq
  • 1,173
  • 7
  • 16
0

I believe the answer may have to do with the fact that you are trying to directly act on a string 1. without using strcpy, and 2. using a pointer array (char*) instead of an array object (char[]) which can cause a segfault.

Sorry, this would better be suited to a comment and not an answer, but I unfortunately can't comment quite yet. This may be of help?

Gummysaur
  • 96
  • 7