Place string in a character array

Asked

Viewed 1,084 times

1

I am learning character matrix and wanted to make a simple program in which I create a character matrix 200x100, put a string at position 0 and printed.

This is part of a larger program that I’m doing, but I need to understand how to insert a string in the character matrix to make.

I know that for the user to enter just put the gets(x[i]), but I need to put by the code.

#include <stdio.h>
#include <conio.h>

int main(){
    char mat[200][100];
    mat[0] = "paulo";
    printf("%s", mat[0]);
    getch();
    return 0;
 }

1 answer

3


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

int main(){
    char mat[200][100];
    strcpy(mat[0], "paulo");
    printf("%s", mat[0]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

You need to manually copy the data from the static area to the stack. Remember that the name can only be up to 99 characters because of the terminator.

It is possible to use pointers and access the content directly in the static area, but it cannot be changed there. It is possible to change the pointer that initially pointed to the static area and then could point to the stack or mount (heap).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.