-1

I'm trying to understand what is wrong here.

void longestConsec(char* strarr[], int n) {
  for(int i=0; i<n; i++)
  {
    printf("%s\n",strarr[i]);
  }
}

int main()
{
    char string[8][14] = {"zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"};
    longestConsec(string, 8);
    return 0;
}

I want to print every single word, and for some reason it doesn't work. What I think of is that strarr is array of pointer to char, so in every cell there should be a word, right? But when i tried to debug the code i saw that strarr and strarr[0] have different memory locations. Why?

2 Answers2

1

strarr is an array of pointers to char, but string is not an array of pointers but an array of 14-element array of chars.

Pointers and 14-element array of chars may have different size, so your code won't work well.

How about using array of pointers like this?

#include <stdio.h>

void longestConsec(const char* strarr[], int n) {
  for(int i=0; i<n; i++)
  {
    printf("%s\n",strarr[i]);
  }
}

int main()
{
    const char* string[8] = {"zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"};
    longestConsec(string, 8);
    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
1

Your compiler should have given you a warning that gives a good hint.

k.c:12:19: warning: passing argument 1 of ‘longestConsec’ from incompatible pointer type [-Wincompatible-pointer-types]
   12 |     longestConsec(string, 8);
      |                   ^~~~~~
      |                   |
      |                   char (*)[14]
k.c:2:26: note: expected ‘char **’ but argument is of type ‘char (*)[14]’
    2 | void longestConsec(char* strarr[], int n) {
      |                    ~~~~~~^~~~~~~~

string is an array of arrays, char[8][14] and strarr is a pointer to pointer to char, char **. When string is passed to the function it decays to pointer to array of 14 char, char (*)[14]. Passing multidimensional arrays to functions can be tricky, but this works:

// size_t is better than int in this case
void longestConsec(size_t len, char strarr[][len], size_t n) 
{
    for(int i=0; i<n; i++)
        printf("%s\n",strarr[i]);
}

And then call it with:

longestConsec(sizeof string[0]/sizeof string[0][0], // 14
              string, 
              sizeof string/sizeof string[0]        // 8
              );

Note that you can write sizeof string[0] instead of sizeof string[0]/sizeof string[0][0] but that's because sizeof char is always 1.

Understanding these declarations can be a bit tricky. Just to give a type example of how they are declared:

char (*arr)[10]; // arr is a pointer to array of char of size 10
char *arr[10];   // arr is an array of 10 pointers to char

Related: arrays are not pointers and pointers are not arrays

klutt
  • 30,332
  • 17
  • 55
  • 95