【发布时间】:2021-07-02 21:47:08
【问题描述】:
我想创建一个 c 程序,当用户输入这样的单词时:“some,words,in,c,proramming。”程序将单词保存在字符串“str”中,然后动态创建一个二维数组并将单词复制到二维数组中:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <math.h>
#include <conio.h>
void freeMememory(int**array, int row){
for(int i=0;i<row;i++)
free(array[i]);
free(array);
}
int lettersCount(char *arr){
int space=0, letters=0;
do{
if(*arr !=' '&& *arr!='\t' && *arr!=','&& *arr!='.'){
letters =letters+1;
}
++arr;
}while(*arr);
return letters;
}
int wordCount(char *arr){
int space=0, words=0;
for(int i=0; arr[i]!='\0'; i++){
if(arr[i] ==' '|| arr[i]=='\t'|| arr[i]=='\n'||arr[i]==','||arr[i]=='.'){
space++;
}
if(space>0){
words++;
space=0;
}
}
return words;
}
int main (){
char arr[100];
int i, j, row, column;
scanf("%[^\n]s", &arr);
int *words = wordCount(arr);
int *letters = lettersCount(arr);
row=words;
column=letters;
int **ptr = (int **)malloc(row*column*sizeof(int));
for(i=0;i<row;i++){ptr[i]=(int*)malloc(column*sizeof(int));}
/*
//how should I write here to copy only words from arr to ptr?
like this:
arr = "some words, two,three,four."
ptr = {
"some", "words", "two", "", "three", "four",
}
*/
freeMememory(ptr, row);
return 0;}
那么任何想法如何只将字符串中的单词复制到二维数组而不复制(句点、空格、cammas)?
【问题讨论】:
-
⟼请记住,尤其是在 Stack Overflow 上学习和提问时,尽可能让代码保持井井有条是很重要的。 Consistent indentation 有助于传达结构,更重要的是,意图,这有助于我们快速找到问题的根源,而无需花费大量时间来尝试解码正在发生的事情。将语句放在一行上确实会使事情变得一团糟。
-
提示:如果您使用
rows甚至rowsCount之类的东西而不是非常具有误导性的row变量,这会有所帮助。 -
int *words = wordCount(arr);将int分配给int*,这是无效的,任何使用它都会导致未定义的行为。 -
@tadman 我编辑了我的代码以便更容易理解。
-
你应该解释一下,代码是用来做什么的,不要让人猜。