将字符串数组传递给函数以从标准输入读取
Passing a Array of strings to function to read from stdin
这段代码让我很紧张!
我有一个由 main 调用的函数,它应该从输入读取到 [5] [20] 的数组 (ArrayStr)(五个单词,每个单词最多 20 个字符)。
但是它在 gets 或 scanf 或 fgets 上崩溃。
#include <stdio.h>
const int MAX_CHARS_STRING = 20;
const int MAX_STRINGS = 5;
int ReadStrings (char **ArrayStr) {
int string_pos = 0;
while (string_pos < MAX_STRINGS) {
gets(ArrayStr[string_pos]);
string_pos++;
}
return 1;
}
int main()
{
int err = 0;
char ArrayStrings[MAX_STRINGS][MAX_CHARS_STRING];
err = ReadStrings (ArrayStrings);
err = WriteStrings (ArrayStrings);
return 0;
}
#include <stdio.h>
const size_t MAX_CHARS_STRING = 20;
const size_t MAX_STRINGS = 5;
//or better
//#define MAX_CHARS_STRING 20
//#define MAX_STRINGS 5
int WriteStrings (size_t rows, size_t cols, char (*ArrayStr)[cols]) {
size_t string_pos = 0;
while (string_pos < rows) {
printf("String No %zu: `%s`\n", string_pos, ArrayStr[string_pos]);
string_pos++;
}
return 1;
}
int ReadStrings (size_t rows, size_t cols, char (*ArrayStr)[cols]) {
size_t string_pos = 0;
while (string_pos < rows) {
if(!fgets(ArrayStr[string_pos], cols, stdin)) return 0;
string_pos++;
}
return 1;
}
int main()
{
int err = 0;
char ArrayStrings[MAX_STRINGS][MAX_CHARS_STRING];
err = ReadStrings (MAX_STRINGS, MAX_CHARS_STRING, ArrayStrings);
err = WriteStrings (ArrayStrings);
return 0;
}
这段代码让我很紧张!
我有一个由 main 调用的函数,它应该从输入读取到 [5] [20] 的数组 (ArrayStr)(五个单词,每个单词最多 20 个字符)。
但是它在 gets 或 scanf 或 fgets 上崩溃。
#include <stdio.h>
const int MAX_CHARS_STRING = 20;
const int MAX_STRINGS = 5;
int ReadStrings (char **ArrayStr) {
int string_pos = 0;
while (string_pos < MAX_STRINGS) {
gets(ArrayStr[string_pos]);
string_pos++;
}
return 1;
}
int main()
{
int err = 0;
char ArrayStrings[MAX_STRINGS][MAX_CHARS_STRING];
err = ReadStrings (ArrayStrings);
err = WriteStrings (ArrayStrings);
return 0;
}
#include <stdio.h>
const size_t MAX_CHARS_STRING = 20;
const size_t MAX_STRINGS = 5;
//or better
//#define MAX_CHARS_STRING 20
//#define MAX_STRINGS 5
int WriteStrings (size_t rows, size_t cols, char (*ArrayStr)[cols]) {
size_t string_pos = 0;
while (string_pos < rows) {
printf("String No %zu: `%s`\n", string_pos, ArrayStr[string_pos]);
string_pos++;
}
return 1;
}
int ReadStrings (size_t rows, size_t cols, char (*ArrayStr)[cols]) {
size_t string_pos = 0;
while (string_pos < rows) {
if(!fgets(ArrayStr[string_pos], cols, stdin)) return 0;
string_pos++;
}
return 1;
}
int main()
{
int err = 0;
char ArrayStrings[MAX_STRINGS][MAX_CHARS_STRING];
err = ReadStrings (MAX_STRINGS, MAX_CHARS_STRING, ArrayStrings);
err = WriteStrings (ArrayStrings);
return 0;
}