首页 > C语言字符串问题

C语言字符串问题

#include<stdio.h>
#include<stdlib.h>
#define max 100
   int main()
   {
    char str1[max],c;
    char str2[max];
    int i,n;

    printf("请输入一串字符串:"); 
    scanf("%s",str1);
    printf("输入插入字符的位置:");
    scanf("%d",&n);
    fflush(stdin);
    printf("要加入的字符:");
    scanf("%c",&c);
    for(int temp=0;temp<=max;temp++)
    {
        str2[temp]=str1[temp]; 
    }
    str1[n]=c;
    str2[n]=c;
    printf("%s,%s",str1,str2);
    system("pause");
    return 0;
}

为什么这里的str1和str2打印出来的结果不一样?
在字符数组的指定位置加入字符的这个程序哪里有问题?求解,谢谢

#include<stdio.h>
#include<stdlib.h>
#define max 100
   int main()
   {
    char str1[max],c;
    char str2[max];
    int i,n;

    printf("请输入一串字符串:"); 
    scanf("%s",str1);
    printf("输入插入字符的位置:");
    scanf("%d",&n);
    fflush(stdin);
    if(n<0||n>max+1)
    {
        printf("输入的位置不合法\n"); 
    }


     for(int temp=0;temp<=max;temp++)
     {
        str2[temp]=str1[temp]; 
     }
        printf("%s",str2);
     for(int j=i=0;str1[i]!='\0';i++,j++)
       {
         if(i>n)
         {
            str2[j+1]=str1[i];
         }
       }

    printf("%s",str2);
    system("pause"); 
    return 0; 
   }

题主的代码太乱了,是个新手吧?看看我重写的,有什么问题随时问我
http://ideone.com/PJeeCS


有点像是考试题目啊。
看来主要是因为字符串长度问题。溢出造成内存问题。
请使用调试工具来排除bug。

对代码建议:

  1. 使用 char cc[256] = {0}; 来初始化字符串。
  2. 使用memcpy来复制字符串

第一个代码,数组长度是100,temp最大是99,在for循环里,temp<max

【热门文章】
【热门文章】