a-sf-d a-sf-d - 1 month ago 8
C Question

C - Calling function of "mixedly allocated" array

I'm a fairly new in C programming and a new member of stackoverflow community, although I'm pretty familiar to tex.stackexchange, and I'm having a syntax problem.

I was wondering how could I allocate one dimension of an array dynamically while having the other allocated statically.
I could find answer in this question. I just need to declare a pointer to an array, and not an array of pointers, as answers tell so. Problem is I can't think of how to call a function of this "mixedly allocated" array (do I have any proper way to call it?) as a parameter, since my variable is declared as follows:

char (*strings)[maxlen];


Where maxlen is a global variable informing each string's length. Then I dynamically allocate it, so I have N strings, each of which with a length
maxlen
:

strings = malloc(N*sizeof(char));


So I would like to call a function of this array of strings, but I can't think of a way to declare it. My first shot was to silly give a try at

void func(char **, int);


and then call

func(strings,N);


But it wouldn't work, because I don't have a
char **
argument, but a
char (*)[100]
(my
maxlen
is 100). So I get the following error:

expected ‘char **’ but argument is of type ‘char (*)[100]’


of course.

Well, my problem could probably be solved if I choose to allocate both dimensions dynamically, but that's not my intention.

How could I declare a function where my variable would go through it without a problem?

Thanks in advance.

EDIT:
maxlen
is a macro, known at compile time.

My minimal example code (not tested yet):

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

#define maxlen 100


void func(char (?), int N);

int main()
{

char (*strings)[maxlen];
int i, N;

scanf("%d", &N);
getchar();
strings = malloc(N*sizeof(char));
for(i=0;i<N;i++)
{
fgets(strings[i],sizeof(strings[i]),stdin);
}

func(strings,N);

return 0;

}

void func(char (?), int N) ...

M.M M.M
Answer

Your question isn't clear whether maxlen is known at compile-time or not. The following code works in both cases. If it is known at compile-time then you don't need to pass it as parameter to func.

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

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

int main()
{
// automatic allocation
    char arr[4][7] = { "Red", "Blue", "Green", "Yellow" };
    func(4, 7, arr);

// dynamic allocation
    int maxlen = 7;
    char (*arr2)[maxlen] = calloc(4, maxlen);
    strcpy(arr2[0], "Red");
    strcpy(arr2[1], "Blue");
    strcpy(arr2[2], "Green");
    strcpy(arr2[3], "Yellow");
    func(4, 7, arr2);
}
Comments