嗨,我有这个程序,逐行读取文本文件,它应该输出每个句子中最长的单词.虽然它在某种程度上起作用,但它用一个同样大的词覆盖了最大的单词,这是我不确定如何解决的问题.编辑此程序时需要考虑什么?谢谢
//Program Written and Designed by R.Sharpe
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "memwatch.h"
int main(int argc, char** argv)
{
FILE* file;
file = fopen(argv[1], "r");
char* sentence = (char*)malloc(100*sizeof(char));
while(fgets(sentence, 100, file) != NULL)
{
char* word;
int maxLength = 0;
char* maxWord;
maxWord = (char*)calloc(40, sizeof(char));
word = (char*)calloc(40, sizeof(char));
word = strtok(sentence, " ");
while(word != NULL)
{
//printf("%s\n", word);
if(strlen(word) > maxLength)
{
maxLength = strlen(word);
strcpy(maxWord, word);
}
word = strtok(NULL, " ");
} …Run Code Online (Sandbox Code Playgroud) 当调用memset时,我对内存中实际发生的事情感到困惑,而当你调用free时会发生什么.
例如,我有一个指向一个char*数组的指针A.
char** A = (char**)calloc(5, sizeof(char*));
int i;
for(i=0;i<5;i++)
{
//filling
A[i] = (char*)calloc(30, sizeof(char));
scanf("%s", &A[i]);
}
Run Code Online (Sandbox Code Playgroud)
现在我想重置它我的char**指针和它指向的所有元素都是完全空的
memset(A, 0, 5);
Run Code Online (Sandbox Code Playgroud)
要么
free(A);
Run Code Online (Sandbox Code Playgroud)
有什么不同?
我对C有点新意,所以请以外行的话说话,谢谢