2

被初中生 C 语言考住了,尴了个尬

 2 years ago
source link: https://www.v2ex.com/t/875942
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  程序员

被初中生 C 语言考住了,尴了个尬

  52coder · 6 小时 37 分钟前 · 3051 次点击

周末来老婆老家,她亲戚有个小孩读初中,有个兴趣班学的 C 语言,得知我是从事软件开发 5 6 年的“高手”,饭后问了我一道编程题,我三俩下就告诉他怎么 怎么写,结果提交的时候始终显示有问题,一排查发现这里有坑,我手写一个 demo (可能编译不过哈)请教各位如下程序输出是什么?

#include <stdio.h>
int main()
{
    int arr[10] = {-1};
    //打印 arr 全部内容
    for(int i = 0;i < 10;i++)
    printf("%d",arr[i]);
    
    return 0;
}

我之前一直以为会全部输出-1 ,结果在 gcc 11.2.0 的环境下,输出确实一个-1 ,然后全是 0.有没有踩过这个坑的朋友?

第 1 条附言  ·  1 小时 58 分钟前

几年没写 C 代码有点脱离一线了,使用 memset 是对每个 byte 操作,针对 int 这里不适用,印象中我司代码中有一些 tricky 的方法,我网上找了个例子,可以变相达到这个目的,评论里有朋友说 memset ,还有我评论的例子 memset(arr,10,sizeof(int)*100)这种是错的,每个字节都设置成 0x10,那么数组每个元素都是 0x10101010
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h> //Use C99 standard for C language which supports bool variables

int main()
{
int i, cnt = 5;
bool *hash = NULL;
hash = malloc(cnt);

memset(hash, 1, cnt);
printf("Hello, World!\n");

for(i=0; i<cnt; i++)
printf("%d ", hash[i]);

return 0;
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK