a-sf-d a-sf-d - 1 year ago 67
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

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


But it wouldn't work, because I don't have a
char **
argument, but a
char (*)[100]
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.

is a macro, known at compile time.

My minimal example code (not tested yet):


#define maxlen 100

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

int main()

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

scanf("%d", &N);
strings = malloc(N*sizeof(char));


return 0;


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

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download