Hello. Just dusting off my function knowladge in relation to pointers for refactoring in a larger project. Came up on this discrepancy. See my verbose debug output. Problem around for loop in function. Short post because adblock wiped my post form two times. :)

#include <stdio.h>

int mult(int x, int y, int *str[]);
int str[5];

int main()
{
    int x,y,i;

    for (i = 0; i < 5; i++) str[i] = i;
    printf("Please input two numbers to be multiplied: ");
    scanf_s("%d", &x);
    scanf_s("%d", &y);
    getchar();
    printf("\nThe product of your two numbers is %d\n", mult(x, y, str));
    getchar();
}

int mult(int x, int y, int *str[])
{
    int o,i;
    for (i = 0; i < 5; i++) {
        printf("\n str[i] before adding x: %d x value: %d", str[i],x);
        str[i] = str[i] + x;
        printf("\n str[i] after adding x: %d", str[i]); }
    o = x * y;
    return o;

}

Edited 1 Year Ago by Ctwo

str is an array of int pointers, but you treat it as if it were an array of int. Is it meant to be an array of int?

What are you using to compile this? Your compiler really should have noticed that and warned you.

Edited 1 Year Ago by Moschops

Comments
Yea it did warn, I just couldn't decypher what it wanted to tell me. :D

More explicitly, you have an array of ints at the top:

int str[5];

...but an array of pointers to int as a parameter:

int mult(int x, int y, int *str[])

You probably want this instead:

int mult(int x, int y, int *str)
Comments
You are good!!
Thanks that worked. I've tried alot of combinations with the brackets and stars, somehow didn't end up using the proper one.

Quick follow-up: if the str were to be an array of two dimensions, eg. str[][] format how would it look like? It doesn't let me keep it the same way in the function header anymore, nor is it happy if I add a set of brackets to compensate for the added(now double) ones.

if the str were to be an array of two dimensions, eg. str[][] format how would it look like?

In a function declaration, only the first dimension size can be omitted. All subsequent dimensions must have a matching size to the array you pass, so it would be something like this:

int mult(int x, int y, int str[][10]);

If you need variable sizes for other dimensions, this is a case where you'll need to simulate an array using pointers completely:

int mult(int x, int y, int **str);

But that changes how you create and use the "array". A proper 2D array won't be compatible with that function signature.

This question has already been answered. Start a new discussion instead.