这是将数字串输入二维数组的好方法吗?我对代码有几个问题:
任务是输入尽可能多的字符串,直到用户输入空字符串为止。然后我需要稍后对字符串进行
标记化
和atoi
。使用一维数组和
char **
会更好/更容易吗?最后,对于
char **
,如果我为字符串分配内存,我是否必须为标记分配更多/不同的内存?int strInput ( char string[][], int maxChars ) { int i = 0; printf("Enter strings of digits. Enter empty string to stop.\n"); while (( string[i][maxChars] = getchar() ) { printf("Please enter a string of digits:"); i++; } string[i] = '\0'; return i; }
最佳答案
char string[][]
K&R 表示法很古老,您确实应该使用"new"char**
样式。
Is this an okay way to input strings of digits into a 2D array?
绝对不是。您正在逐个字符读取字符,而不是逐个数字字符串读取数字字符串,我认为您的意图是这样。
Would it be better / easier to use 1D array and a char ** to do it?
也可以那样做,在同一个字符串中的项目之间写一些标记。这基本上取决于您。
And last, with the char **, if I allocate memory for the strings, do I have to allocate more / different memory for the tokens?
是的,当然,您要么预先分配非常大的内存,要么不断重新分配。
关于c - *C* 可接受的二维字符串输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27329530/