c - 这个程序的输出是什么?为什么?

标签 c

希望这个程序输出“Digi”,但为什么它输出“Dig)tal孟加拉国”。

谁能解释一下吗?

#include<stdio.h>

int main(){

char str[120]="Digital Bangladesh";
int n;
n=strlen(str);
printf("%d \n",n);
str[4]="\0";
printf("%s",str);
return 0;
}

最佳答案

我在评论中给出了基本解释,并稍微改进了您的代码(将 "\0" 替换为 '\0' 并包含 string.h for strlen())。

#include <stdio.h>
#include <string.h>

int main() {
    char str[120] = "Digital Bangladesh";
    int n = strlen(str);  // can combine declaration and assignment into a single statement; 
                          // this will assign the actual length of string str to n
    printf("%d \n", n);
    str[4] = '\0';      // shouldn't be "\0" since anything in double quotes will be a string and not a character
                        // you are assigning 5th character (4th index + 1) of str to NULL ('\0') terminator character; 
                        // now str will have content "Digi"
    printf("%s", str);
    return 0;
}

关于c - 这个程序的输出是什么?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56911660/

相关文章:

c - 如何系统地遵循递归?

无法在 visual studio 2008 中构建 CUDA 项目

c# - 将 byte[] 从 c# 传递到纯 c dll 时发生访问冲突

c++ - WinDivert - 修改数据包数据/负载内容

c++ - 分解在 Visual C++ 中不起作用的函数

C 链表函数程序遇到段错误

python - Python 中更节省内存的结构表示?

c - linux c-pthreads : problem with local variables

c - C中线程同步和条件变量的问题

c - 数组指针地址