简体   繁体   中英

Beginner in C, array of strings

I'm trying to copy a string to a cell in array of strings. I know it's a simple question, but I can't figure out why strcpy copies only the first char.

Please explain to a beginner :)

Something idiotic like this:

#include <stdio.h>
#include <string.h>
#define MAX_LINE_LENGTH     10
#define MAX_INPUTS  3


void func(char array[MAX_INPUTS][MAX_LINE_LENGTH])
{
    char line[MAX_LINE_LENGTH];
    fgets(line, MAX_LINE_LENGTH, stdin);
    strcpy(array[0], line);
}


int main(int argc, char *argv[])
{
    char lines[MAX_INPUTS][MAX_LINE_LENGTH];
    func(lines);
    return 0;
}

Your code works for me (I made tiny adjustments) :

$ cat test.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 10
#define MAX_INPUTS 3

void func(char array[MAX_INPUTS][MAX_LINE_LENGTH]){
    char line[MAX_LINE_LENGTH];
    fgets(line, MAX_LINE_LENGTH, stdin);
    strcpy(array[0], line);
}

/* no need to use main args in this case */
int main(void){
    char lines[MAX_INPUTS][MAX_LINE_LENGTH];
    func(lines);
    printf("str=%s\n", lines[0]);
    return EXIT_SUCCESS;
}
$ gcc test.c -Wall -Wextra
$ ./a.out
something
str=something

Maybe it was your print which was wrong (wrong format, etc.) ?

Here: I modified the functions so that the memory is passed by reference:

#include <stdio.h>
#include <string.h>
#include <stdlib.h> //for malloc
#define MAX_LINE_LENGTH     10
#define MAX_INPUTS  3

void func(char **array)
{
    char line[MAX_LINE_LENGTH];
    fgets(line, MAX_LINE_LENGTH, stdin);
    strcpy(array[0], line);
}

int main(int argc, char *argv[])
{
    int i;
    char **lines = malloc(MAX_INPUTS); //allocate it on the stack so it can be changed easier
    for (i = 0; i < MAX_INPUTS; i++)
        lines[i] = malloc(MAX_LINE_LENGTH * sizeof(*lines)); //allocate a multidimensional array
    func(lines);
    printf("%s\n", lines[0]);
    return 0;
}

Hope this helps

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