strcpy() and arrays of strings

蹲街弑〆低调 提交于 2019-12-05 19:12:16

You need to allocate space for the string. This can be done several ways, the two leading contenders look like:

char history[10][100];

and

char *history[10];
for (j = 0;  j < 10;  ++j)
    history [j] = malloc (100);

The first statically allocates ten character buffers at 100 characters each. The second, as you wrote it, statically allocates ten pointers to characters. By filling in the pointer with dynamically allocated memory (which could each be arbitrary lengths), there is memory to read the string later.

strcpy() does not allocate new memory area for the string, it only copies data from one buffer to another. You need to allocate new buffers using strdup() or create the array pre-allocated (char history[10][100];). In this case, do not try to move pointers and use strcpy to copy the data.

main.c:11: error: incompatible types in assignment
(Code: input = "input";)

This happens because you try to make the array 'input' point to the string "input". This is not possible, since the array is a const pointer (i.e. the value it points to can not change).

The correct way to do what you are trying is:

strcpy(input,"input");

Of course this is a minor problem, the major problem has already been posted twice. Just wanted to point it out.

Btw I don't know how you even compile this when running it on the terminal. Don't you get an error? Maybe just a warning? Try compiling with -Wall -pedantic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!