我正在做 Zed Shaw 的Learn C The Hard Way课程。在练习 11 中,在额外学分问题 #2 中,他问:
使用 i-- 从 argc 开始倒数到 0,使这些循环倒数。您可能需要做一些数学运算才能使数组索引正常工作。
使用 while 循环将值从 argv 复制到状态。
我尝试:
#include <stdio.h>
int main(int argc, const char *argv[]){
int i = argc - 1;
while(i >= 0){
printf("arg %d: %s\n", i, argv[i]);
i--;
}
char *states[] = {
"California", "Oregon",
"Washington", "Texas"
};
int num_states = 4;
i = num_states - 1;
while( i >= 0){
printf( "state %d, %s\n", i, states[i]);
i--;
}
i = 0;
while(i < argc && i < num_states){
int j = 0;
while( (states[i][j++] = argv[i][j++]) != '\0' ){
i++;
}
states[i][j] = '\0';
}
i = num_states - 1;
while( i >= 0){
printf( "state %d, %s\n", i, states[i]);
i--;
}
return 0;
}
我得到一个Segmentation Fault
. 我知道您不能在 C 中复制数组,它们是 const 指针或类似的东西(或者我读过)。这就是为什么我尝试逐个字符地复制:
while(i < argc && i < num_states){
int j = 0;
while( (states[i][j++] = argv[i][j++]) != '\0' ){
i++;
}
states[i][j] = '\0';
}
然而它不起作用。我该怎么做?当我编译时,编译器给了我这个警告:
$ make ex11
cc -Wall -g ex11.c -o ex11
ex11.c: In function ‘main’:
ex11.c:26:28: warning: operation on ‘j’ may be undefined [-Wsequence-point]
我不明白为什么它说这j
是未定义的。 valgrind
说:
$ valgrind ./ex11 this is a test
==4539== Memcheck, a memory error detector
==4539== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==4539== Using Valgrind-3.8.0 and LibVEX; rerun with -h for copyright info
==4539== Command: ./ex12 this is a test
==4539==
arg 4: test
arg 3: a
arg 2: is
arg 1: this
arg 0: ./ex11
state 3, Texas
state 2, Washington
state 1, Oregon
state 0, California
==4539==
==4539== Process terminating with default action of signal 11 (SIGSEGV)
==4539== Bad permissions for mapped region at address 0x400720
==4539== at 0x4005F1: main (ex11.c:26)
==4539==
==4539== HEAP SUMMARY:
==4539== in use at exit: 0 bytes in 0 blocks
==4539== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==4539==
==4539== All heap blocks were freed -- no leaks are possible
==4539==
==4539== For counts of detected and suppressed errors, rerun with: -v
==4539== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
Segmentation fault
[编辑 1] 为此切换了我的代码
int i = 0;
while( i < argc && i < num_states ){
states[i] = argv[i];
i++;
}
它确实有效,但编译器给了我一个警告。另外,我在发布这个问题后意识到我以前的问题:
while( (states[i][j++] = argv[i][j++]) != '\0' ){
i++;
}
完全是错误的。因为j++
每个循环执行两次,并且i++
应该在外循环中的该循环之外。而且正如下面评论中提到的,我尝试使用数组数组进行的逐字节复制不起作用,因为我实际上有指针数组。
也就是说,有没有办法在没有编译器警告的情况下做到这一点?