这是我编写的程序中的主要函数,我需要在其中对字符数组进行排序,使字符在开头具有偶数 ascii 代码,并且我想显示数组在每次迭代时的排序方式。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main ()
{
int n, i,j;
char echange;
printf("array size : ");
scanf("%d", &n);
char t[n];
for (i=0; i<n; i++)
{
printf("enter array elements : ");
scanf(" %c", &t[i]);
}
for (j=0; j<n; j++)
for (i=0; i<n; i++)
{
if ((t[i] % 2!=0) && (t[i+1] % 2 ==0) && (i != n-1))
{
strcpy(echange, t[i]);
strcpy(t[i], t[i+1]);
strcpy(t[i+1], echange);
printf (" %c (%d)", t[i], t[i]);
}
else
printf(" %c (%d)", &t[i], t[i]);
}
}
这个问题编译正常,但是输出的很奇怪:
array size : 3
enter array elements : d
enter array elements : f
enter array elements : g
2 └ (100) ┴ (102) ┬ (103) └ (100) ┴ (102) ┬ (103) └ (100) ┴ (102) ┬ (103)
Process returned 0 (0x0) execution time : 4.063 s
Press any key to continue.
那么我的代码有什么问题呢?以及为什么如何将 strcpy 与单个字符一起使用?顺便说一句,我试过没有 strcpy 函数:
echange = t[i];
t[i] = t[i+1];
t[i+1] = echange;
也没有用
最佳答案
strcpy
函数用于将空终止字符串从一个 char
数组复制到另一个数组。你正在做的是复制单个字符,所以你将无效参数传递给函数,触发 undefined behavior .
对于单个字符,您可以直接分配给它们。
echange = t[i];
t[i] = t[i+1];
t[i+1] = echange;
关于c - 是否可以将 strcpy 与单字符变量一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70277766/