结构中的 C 2 维字符

标签 c arrays struct char variable-assignment

我正在尝试将输入读取到 2dim char 结构成员中,

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

enum { HIGHT=14, WIDTH=147, IMAGES=24 };

typedef struct{
    char *frame[HIGHT][WIDTH];
    int fps;
} frame_stack_t;

void out(frame_stack_t *frame_stack[IMAGES]);

int main(){
    frame_stack_t *frame_stack[IMAGES];

    for (int i=0; i<IMAGES; i++){
        for (int j=0; j<HIGHT; j++){
            strcpy( frame_stack[i]->frame[j], "some text" );
        }
    }

    out(frame_stack);
}

void out(frame_stack_t *frame_stack[IMAGES]){
    for (int i=0; i<IMAGES; i++){
        for (int j=0; j<HIGHT; j++){
            printf("%s",frame_stack[i]->frame[j]);
        }
    }
}

它看起来对我来说是正确的,但我收到以下输出:

test_struct.c: In function ‘main’:
test_struct.c:19:25: warning: passing argument 2 of ‘strcpy’ from incompatible pointer type [-Wincompatible-pointer-types]
    strcpy( "some text", frame_stack[i]->frame[j] );
                         ^
In file included from test_struct.c:3:0:
/usr/include/string.h:125:14: note: expected ‘const char * restrict’ but argument is of type ‘char **’
 extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
              ^
test_struct.c: In function ‘out’:
test_struct.c:29:11: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’ [-Wformat=]
    printf("%s",frame_stack[i]->frame[j]);
           ^
Speicherzugriffsfehler

gdb 告诉我 strcpy 失败

Program received signal SIGSEGV, Segmentation fault.
__strcpy_sse2_unaligned () at ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:546
546 ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S: Datei oder Verzeichnis nicht gefunden.

有人可以告诉我这里出了什么问题吗?

最佳答案

所涉及的 C 代码有很多问题。在将问题发布到这样的开放论坛之前,请先阅读并练习。请参阅下面更正后的代码并尝试理解:

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

enum { HIGHT=14, IMAGES=24, WIDTH=147 };

typedef struct{
char frame[HIGHT][WIDTH];
int fps;
} frame_stack_t;

void out(frame_stack_t *frame_stack);

int main()
{
frame_stack_t frame_stack[IMAGES];
int i, j;

for (i=0; i<IMAGES; i++)
{
    for (j=0; j<HIGHT; j++)
    {
        strcpy(frame_stack[i].frame[j], "some text\n" );
    }
}

out(frame_stack);
}

void out(frame_stack_t frame_stack[])
{
int i,j;
for (i=0; i<IMAGES; i++)
{
    for (j=0; j<HIGHT; j++)
    {
        printf("%s",frame_stack[i].frame[j]);
    }
}
}

关于结构中的 C 2 维字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44140242/

相关文章:

javascript - javascript数组的快速分组

c - 如何在 C 中将 union 指针作为参数传递? union 的内部是什么?

涉及管道的c并行进程

java - JNI 无法识别 jni 原始类型,例如字符串

arrays - 上下文类型 'Emoji' 不能与数组文字一起使用

c# - 如何在 C++/CLI 或 C# 中将静态结构数据保存到二进制文件

c# - 将字节数组的 C++ 结构转换为 C#

c++ - 共享内存执行得这么快?

c - 寻找重叠的算法

arrays - 如何在 Kotlin 中将 String 数组转换为 Int 数组?