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;

}

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.

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

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)
commented: Thanks that worked. I've tried alot of combinations with the brackets and stars, somehow didn't end up using the proper one. +0
commented: You are good!! +0

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.

gusano79, you are good to find errors...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.