-1

I got an assignment from my teacher to write a code that compares a given word to a bunch of words located in an array of strings. If the word in the array is lexicography smaller than the word given, I need to put it inside a new array. else, I'm moving to the next word. for example; given word: hello arr=bus, alpha, world, java. new array=bus,alpha. I wrote a code that does that using STRCMP, but the computer throws me out when it gets to the strcpy part. this is my code

char** LowerSTR(char* arr[], int size_arr, char* str, int* size_res)

size_res = 0;
char** newArr= (char**)calloc(size_arr, sizeof(char));
for (int i = 0; i < size_arr; i++)
{
    if (strcmp(str, arr[i])==1)
    {
        for (int k = 0; k <size_arr;k++)
        {
            strcpy(newArr[k], arr[i]);
        }
        size_res++;
    }
}
if (size_res == 0)
    return NULL;
else return newArr;}

maybe I should use STRCAT instead?

please help :\

Kfir Bilu
  • 29
  • 8
  • When you say "the computer throws me out" what exactly do you mean? Is there a seg fault? What error message do you receive? – kopecs Dec 24 '19 at 17:40
  • Exception thrown at 0x0102EE72 (ucrtbased.dll) in 11111.exe: 0xC0000005: Access violation writing location 0x00000000. – Kfir Bilu Dec 24 '19 at 17:43

2 Answers2

1

In calling strcpy with newArr[k] as an argument you're dereferencing a NULL pointer.

Recall that we allocate newArr as follows:

char** newArr= (char**)calloc(size_arr, sizeof(char));

There's actually multiple errors here. The first is that we calloc with sizeof(char) when we in fact want a region of char*s. So corrected1 we have

char** newArr= calloc(size_arr, sizeof(char*));

As we've calloc'd this piece of memory, all of it is zeroed. Thus when strcpy internally accesses newArr[k] (itself of type char*) it points to memory address 0, which is likely reversed by the OS, and in any case, not a valid address in the context of our program.

In order to resolve this, we need to allocate for each string. For instance, one might do

newArr[k] = malloc(strlen(arr[i]) + 1); // The +1 is for the \0 termination character

the line before we strcpy.

You also have a bug with size_res as you just treat it as an int instead of an int* as you need to dereference it when you want to change or read the value to which it points.

1 See here for why I've removed the cast.

kopecs
  • 1,545
  • 10
  • 20
  • Thanks!! All the problems are gone, but im not getting the result i need. how do i print the new array after the changes? – Kfir Bilu Dec 24 '19 at 20:28
0

You should scan newArr and print all strings inside, something like:

for (int i = 0; i < *size_res; i++) // !
{
   printf("%s\n",newArr[i]);
}

(!) 'size_res' is passed to the function as a pointer to int,

risbo
  • 188
  • 7