0

The program displays the multiplication table. When compiling, it gives the following errors:

solution.c: 46: 13: warning: incompatible pointer types returning 'char [10] [12]' from a function with result type 'char *' [-Wincompatible-pointer-types] return mul;

solution.c: 46: 13: warning: address of stack memory associated with local variable 'mul' returned [-Wreturn-stack-address] return mul;

I know there is a problem with pointers. Help me to understand

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

char *mulTable(int x) {
    char mul[10][12];
    char m = '*';
    char eq = '=';
    char pr = ' ';
for (int i = 0; i<11; i++) {
        if ((i+1) == 10) {
            mul[i][0] = '1';
            mul[i][1] = '0';
            mul[i][2] = pr;
            mul[i][3] = m;
            mul[i][4] = pr;
            mul[i][5] = x+'0';
            mul[i][6] = pr;
            mul[i][7] = eq;
            mul[i][8] = pr;
            mul[i][9] = (((i+1)*x)/10)+'0';
            mul[i][10] = (((i+1)*x)%10)+'0';
            mul[i][11] = '\0';
            continue;
        }
        mul[i][0] = (i+1)+'0';
        mul[i][1] = pr;
        mul[i][2] = m;
        mul[i][3] = pr;
        mul[i][4] = x+'0';
        mul[i][5] = pr;
        mul[i][6] = eq;
        mul[i][7] = pr;
        if ((((i+1)*x)/10) == 0) {
            mul[i][8] = (((i+1)*x)%10)+'0';
            mul[i][9] = '\0';
            continue;
        }
        mul[i][8] = (((i+1)*x)/10)+'0';
        mul[i][9] = (((i+1)*x)%10)+'0';
        mul[i][10] = '\0';
        }
        return mul;
    /*for (int i = 0; i<10; i++) {
        printf("%s\n", mul+i);
    }*/
}

int main() {
mulTable(7);
    
    
    return 0;
}`

1 Answers1

0

You can't return arrays in C. You could return a pointer to a dynamically allocated array, but the best solution here is likely to use a struct.

typedef struct
{
  char mul[10][12];
} mul_table_t;

...

mul_table_t get_mul_table (int x);

Returning structs by value is fine.

Though consider if there's a reason why these can't be read-only const look-up tables instead? In that case you could declare everything as static const at local scope and return a const qualified pointer.

Lundin
  • 195,001
  • 40
  • 254
  • 396