Если вы получаете это сообщение во время сохранения или компиляции сборки, просто закройте все файлы, а затем откройте любой файл для компиляции и сохранения.
Для меня причина в том, что я переименовал файл, и старый файл все еще был открыт.
Так же, как идея другого стиля манипуляции с строками в C, вот пример, который не изменяет исходную строку и не использует malloc
. Чтобы найти пробелы, я использую функцию libc strpbrk
.
int print_words(const char *string, FILE *f)
{
static const char space_characters[] = " \t";
const char *next_space;
// Find the next space in the string
//
while ((next_space = strpbrk(string, space_characters)))
{
const char *p;
// If there are non-space characters between what we found
// and what we started from, print them.
//
if (next_space != string)
{
for (p=string; p<next_space; p++)
{
if(fputc(*p, f) == EOF)
{
return -1;
}
}
// Print a newline
//
if (fputc('\n', f) == EOF)
{
return -1;
}
}
// Advance next_space until we hit a non-space character
//
while (*next_space && strchr(space_characters, *next_space))
{
next_space++;
}
// Advance the string
//
string = next_space;
}
// Handle the case where there are no spaces left in the string
//
if (*string)
{
if (fprintf(f, "%s\n", string) < 0)
{
return -1;
}
}
return 0;
}
Вы должны быть malloc'ing strlen (ptr), а не strlen (buf). Кроме того, ваш count2 должен быть ограничен числом слов. Когда вы дойдете до конца своей строки, вы продолжаете перебирать нули в своем буфере и добавляете нулевые строки в свой массив.
Подумайте, используя strtok_r
, как предложили другие, или что-то вроде:
void printWords(const char *string) {
// Make a local copy of the string that we can manipulate.
char * const copy = strdup(string);
char *space = copy;
// Find the next space in the string, and replace it with a newline.
while (space = strchr(space,' ')) *space = '\n';
// There are no more spaces in the string; print out our modified copy.
printf("%s\n", copy);
// Free our local copy
free(copy);
}
Что-то не так: get_words()
всегда возвращает один меньше фактического количества слов, поэтому в итоге вы пытаетесь:
char *newbuff[words]; /* Words is one less than the actual number,
so this is declared to be too small. */
newbuff[count2] = (char *)malloc(strlen(buffer))
count2
, в конце концов, всегда больше, чем число элементы, которые вы указали для newbuff[]
. Почему malloc()
не возвращает действительный ptr, хотя, я не знаю.
malloc(0)
может (необязательно) возвращать NULL
, в зависимости от реализации. Вы понимаете, почему вы можете называть malloc(0)
? Или, точнее, вы видите, где вы читаете и пишете размер вашего массива?
char arr[50];
gets(arr);
int c=0,i,l;
l=strlen(arr);
for(i=0;i<l;i++){
if(arr[i]==32){
printf("\n");
}
else
printf("%c",arr[i]);
}
Для удовольствия здесь представлена реализация, основанная на обратном вызове:
const char* find(const char* s,
const char* e,
int (*pred)(char))
{
while( s != e && !pred(*s) ) ++s;
return s;
}
void split_on_ws(const char* s,
const char* e,
void (*callback)(const char*, const char*))
{
const char* p = s;
while( s != e ) {
s = find(s, e, isspace);
callback(p, s);
p = s = find(s, e, isnotspace);
}
}
void handle_word(const char* s, const char* e)
{
// handle the word that starts at s and ends at e
}
int main()
{
split_on_ws(some_str, some_str + strlen(some_str), handle_word);
}