gpt4 book ai didi

c - 访问数组的特定元素

转载 作者:行者123 更新时间:2023-11-30 15:32:13 25 4
gpt4 key购买 nike

我正在尝试创建一个 C 程序来创建一个小的单词列表 .txt 文件。我创建了包含 10 个元素的 char 数组,并且我需要这 10 个字符的所有可能的 4 个字母组合。

所以,我想在彼此内部有 4 个 for 循环,以从该数组中获取元素并创建 4 个字母组合并将其写入 .txt。

我的问题是使用指针访问数组的元素。我正在做:

char array[10] = {'A', 'S' ,'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M'};
char input[4];
char *p;
p=array;
FILE *pFile = NULL;
char *filename = "output.txt";
pFile = fopen(filename, "w");

for(i=0;i=3;i++) {
for(j=0;j=3;j++) {
for(k=0;k=3;k++) {
for(l=0;l=3;l++) {
strcpy(input, *(p+i));
strcat(input, *(p+j));//"gluing" first and second element of new string together
strcat(input, *(p+k));//same as line before
strcat(input, *(p+l));
strcat(input, "\n");
fprintf(pFile, input);

//end of for loops, closing .txt file etc.

这可以很好地编译并启动终端,但随后崩溃。我认为这是因为访问数组元素时出现一些错误。

有什么想法吗?非常感激!

其他信息>当我创建时:

char string[10] = "assd";
//and insert that instead of *(p+i) anywhere it works as it is supposed to

最佳答案

strcpystrcat 都会继续执行,直到找到 NULL,而您的数组没有 NULL。数组中的每个槽都是一个字符,后面跟着下一个字符,依此类推。因此 strcpy 将从所选字母开始复制,直到超出整个列表的末尾。最后,您还要向 4 元素数组添加第 5 个元素(“\n”)。相反,请执行以下操作:

input[0] = *(p+i);
input[1] = *(p+j);
input[2] = *(p+k);
input[3] = *(p+l);
input[4] = "\n";

这应该有效。但请注意,fprintf 可能是一种更简单的方法:

fprintf(pFile, "%c%c%c%c\n", *(p+i), *(p+j), *(p+k), *(p+l));

我很想继续用你的代码玩“代码高尔夫”,因为从长远来看,有很多事情可以改进它,但我想我会停止让它工作(尽管我发现它)令人惊讶的是,您的编译器接受第一行,而不使用引号列出字母,例如 'A')。最后还有一点:您根本不需要 p 变量。实际上,您可以像 *(p+i]) 一样轻松地在上面执行 array[i]

关于c - 访问数组的特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24341847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com