我正在尝试将输入读取到 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/