我正在使用数组,我已经将字符串数组传递给函数以及使用字符串和整数数组进行其他位操作。
现在,我对 strcpy
有疑问,我做了什么并且想知道:
- 如果我分配
strcpy(temp, str1[i]);
而temp
是char *temp
,则会崩溃。 单字符串数组
temp[100]
。但是,我没有弄清楚如何计算数组的字符串元素的temp
的大小。我知道我必须给出 17 作为temp
的大小,以便适合字符串数组中的字节。 喜欢:char *temp[17];
然后,我可以应用strcpy(temp, str1[i]);
其中*str1[] = {"sweepsweepsweepsweep"}
20 个字符。大小为 16 时会崩溃。我无法将 stings 数组的一个成员分配给另一个成员。 但我看到一个代码可以做到这一点。
另一件事就是为什么如果我声明其他空字符串数组
str2
和str3
,它们的值与str1
相同?它包含在代码示例的末尾。
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdint.h>
int main()
{
int m = 0, j = 1, n, i;
char *str1[] = {"sweep", "forward"}, *str2[] = {}, *str3[] = {}, *temp;
uint8_t cnt = sizeof(str1) / sizeof(str1[0]);
if (strcmp(str1[m], str1[j]) > 0) {
strcpy(temp, str1[m]);
strcpy(str1[m], str1[j]);
strcpy(str1[j], temp);
printf("OK\n");
} else {
printf("NOPE\n");
}
printf("The sorted string\n");
for (i = 0; i < cnt; i++)
puts(str1[i]);
printf("%d\n", strcmp(str1[0], str1[1]));
printf("-----------------\n");
printf("temp: %s\n", temp);
printf("str2: %s\n", str2[0]);
printf("str3: %s\n", str3[0]);
return 0;
}
在线代码示例:
#include<stdio.h>
int main(){
int i,j,n;
char str[20][20],temp[20];
puts("Enter the no. of string to be sorted");
scanf("%d",&n);
for(i=0;i<=n;i++)
gets(str[i]);
for(i=0;i<=n;i++)
for(j=i+1;j<=n;j++)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("The sorted string\n");
for(i=0;i<=n;i++)
puts(str[i]);
return 0;
}
最佳答案
我认为你的错误是因为 temp 是一个指针,而你将它用作字符串(Char 数组)
当您调用 strcpy(str1[j],temp)
时,我认为问题就出在这里。
另请注意,在线解决方案不使用 *temp 指针,而是使用数组
关于c - 带字符串数组的 strcpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39124325/