小编Jug*_*gni的帖子

可以使用fseek(stdin,1,SEEK_SET)或倒带(stdin)来刷新输入缓冲区而不是非便携式fflush(stdin)吗?

由于我发现fflush(stdin)不是一种可移植的方式来处理熟悉的"新行潜伏在输入缓冲区中"的问题,所以当我必须使用时,我一直在使用以下内容scanf:

while((c = getchar()) != '\n' && c != EOF);
Run Code Online (Sandbox Code Playgroud)

但今天我偶然发现了我在cflplus.com上关于fflush注意到的这一行:

fflush()...在打开以进行更新的文件中(即,打开以进行读取和写入),在执行输入操作之前,应在输出操作之后刷新流.这可以通过重新定位(fseek,fsetpos,rewind)或通过显式调用fflush来完成

事实上,我已经多次阅读过了.所以我想确认一下,我是否可以简单地使用以下任何一种方法,scanf()以便在fflush(stdin)支持时提供同样的服务:

fseek(stdin,1,SEEK_SET);
rewind(stdin);
Run Code Online (Sandbox Code Playgroud)

PS rewind(stdin)似乎非常安全,可以刷新缓冲区,我错了吗?

错误我应该提到,fseek(stdin,0,SEEK_SET)如果我们正在讨论,stdin因为我们不能使用0或0之外的任何偏移量ftell().

c fseek fflush input-buffer

6
推荐指数
1
解决办法
2960
查看次数

为什么我被允许在C中使用const限定变量作为数组大小?

当我运行以下代码时,它适用于C:

#include<stdio.h>

int main(void)
{

const int x=5;
char arr[x];
printf("%d",sizeof(arr));

}
Run Code Online (Sandbox Code Playgroud)

但是,不仅我之前读过const合格的变量不是real常量(这就是为什么它们不能在case条件下使用switch-case),但IBM的以下链接证实了(IBMLINK)并说:

 const int k = 10;
 int ary[k];     /* allowed in C++, not legal in C */
Run Code Online (Sandbox Code Playgroud)

为什么我允许const在C中使用合格变量作为数组大小而没有任何错误?

c arrays const constants lifetime

5
推荐指数
1
解决办法
680
查看次数

realloc()问题:旧块的释放,旧大小的新大小,以及传递静态数组基址

虽然读到realloc()我已经偶然发现了一些我需要澄清而不是忽视的疑问.你的答案非常受欢迎.为了清楚起见,我把它们放在一个编号列表中.请不要介意这个问题的长度.

1)在使用时realloc(),如果内存块及其内容被移动到一个新位置,那么orignal地址是否会被解除分配,好像我们在其上调用了free()?我已经从中读过以下cplusplusreference内容了realloc,但是它们接近于建议原始内存块在这种情况下确实被取消分配,但我需要您的确认.

->C90 (C++98)C99/C11 (C++11) Otherwise, if size is zero, the memory previously allocated at ptr is deallocated as if a call to free was made, and a null pointer is returned.

->If the function fails to allocate the requested block of memory, a null pointer is returned, and the memory block pointed to by argument ptr is not deallocated (it is still valid, and with its contents unchanged). …

c memory-management realloc dynamic-memory-allocation

3
推荐指数
1
解决办法
3561
查看次数

如果C99解除了"块顶部的变量声明"约束,为什么在"for循环"中显示错误呢?

我从一个网站上读到C99解除了限制,即C中的变量必须在块的顶部声明.我在下面的程序中测试过,确实如此,因为我没有错误.但是在同一个程序中如果我在for循环的第一个语句中声明一个变量,我得到错误:

'for' loop initial declarations are only allowed in C99 mode|

这里有两件事.确实允许在程序中间声明变量,正如我所做的那样i,为什么我不允许在for循环语句中执行此操作?第二,如果我的编译器(Codeblocks/gcc)已经不在C99模式,为什么我在中间而不是顶部声明变量时没有出错?

#include <stdio.h>

int main (void)
{
  //Proof that initialization in middle works (for i)
  printf("Enter\n");
  char string[20];
  scanf("%s", string);
  int i=20;
  printf("%s,%i", string, i);
  //Proved that it works

  for(int j=0; j<10; j++) //THIS IS NOT ALLOWED
    printf("%d\n", j);
}
Run Code Online (Sandbox Code Playgroud)

c for-loop c99 variable-declaration

1
推荐指数
1
解决办法
881
查看次数

为什么7%-5给出2但-7%5给-2?这两种情况都不应该是-2吗?

请解释以下原因,数学上正确的答案是-2两种情况:

int a=7%-5; //Assigns 2 to a
int a=-7%5;  //Assigns -2 to a
Run Code Online (Sandbox Code Playgroud)

代码在C中.

c modulo

0
推荐指数
1
解决办法
543
查看次数