我得到一個分段錯誤不能strcpy分段錯誤
所以在頂部我有typedef字符*字符串;
然後我只是有一個設置爲STR約5
for(i=0; i<=spaces; i++) {
sepwords[i] = malloc(3000);
}
變量稱爲空間是一個字符數組,我期待的空間和複製到那時
while(str[i]!=' ') {
printf("%d\n", i);
strcpy(sepwords[i], "hello");
i++;
}
使實際工作
但是如果我做
while(str[i]!=' ') {
char *temp[100];
*temp=str[i];
printf("%d\n", i);
strcpy(sepwords[i], *temp);
i++;
}
它seg seg在此
我不認爲這是因爲我使用typedef字符串,因爲我事先分配內存。
有什麼想法?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINE 256
char *progn;
void usage(void) {
fprintf(stderr, "Usage: %s pattern\n", progn);
}
typedef char * string;
int pattern_match(char *pattern, char *str) {
int i=0;
int spaces=0;
while(str[i]!=0) {
if(str[i]==' ') {
spaces++;
}
i++;
}
string sepwords[spaces];
for(i=0; i<=spaces; i++) {
sepwords[i] = malloc(3000);
}
i=0;
while(str[i]!=' ') {
char *temp[100];
*temp=str[i];
printf("%d\n", i);
strcpy(sepwords[i], temp);
i++;
}
//printf("%d\n", spaces);
//strs[0]="hiya boy";
//printf(strs[1]);
}
int main(int argc, char **argv) {
char line[MAXLINE];
char *pattern;
progn = argv[0];
if (argc != 2) {
usage();
return EXIT_FAILURE;
}
pattern = argv[1];
while (!feof(stdin) && !ferror(stdin)) {
if (!fgets(line, sizeof (line), stdin)) {
break;
}
if (pattern_match(pattern, line)) {
printf("%s", line);
}
}
if (ferror(stdin)) {
perror(progn);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
在哪個平臺上?嘗試內存調試器工具。 – Zaffy 2013-02-27 22:34:45
我認爲你沒有掌握C語言的語義和可能的語法。一個有用的技巧是從標識符開始讀取它們,然後通過任意括號,然後通過* s和qualifers,所以char * temp [100]讀作「temp是一個100個指向char的指針的數組」 – Clyde 2013-02-27 22:36:02
我想建議你解釋你實際想要達到的目標。從您發佈的代碼片段中不明顯。 – Clyde 2013-02-27 22:37:34