简体   繁体   中英

How to pass 2d array of string to the function and print value of it?

Why it is not working... It should be working, right? gcc have problem with this line, but why?

render_history(history, 2);

Sorry for bothering. I am just a beginner.

 #include <stdio.h>

void render_history(char** history, const int entry);

int main()
{
char* history[3][4];

history[0][0] = "1234";
history[1][0] = "5678";
history[2][0] = "9012";

render_history(history, 2); //??
return 0;
}


void render_history(char** history, const int entry)
{
// print "9012" 
}

gcc have problem with this line, but why?

Because the type is wrong. char* history[3][4]; can't be passed as char** . They are incompatible types.

Try something like:

#include <stdio.h>

void render_history(char* (*history)[4] , const int entry)
{
   printf("%s\n", history[entry][0]);
} 

int main()
{
    char* history[3][4];

    history[0][0] = "1234";
    history[1][0] = "5678";
    history[2][0] = "9012";

    render_history(history, 2);
    return 0;
}

As mentioned above double pointer not equal to 2D array. You can also use pointer to pointer of char. char **history . And with this you have several option:

1) Use compound literals

#include <stdio.h>

void render_history(const char **history, const int entry)
{
    printf("%s\n", history[entry]);
}

int main(void)
{
    const char **history = (const char *[]) { "1234", "5678", "9012", NULL};
    render_history(history, 2);  
    return 0;
}

If you need change your data later

2) Use dynamic memory allocation with malloc

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

void render_history(char **history, const int entry)
{
    printf("%s\n", history[entry]);
}

int main(void)
{
    char **history = malloc(3 * sizeof(char *));

    for (int i = 0; i < 3; ++i)
    {
        history[i] = malloc(4 * sizeof(char));
    }

    strcpy(history[0], "1234");
    strcpy(history[1], "5678");
    strcpy(history[2], "9012");
    history[3] = NULL;

    render_history(history, 2);
    return 0;
}

If you use 2nd option dont forget free memory after use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM