相关疑难解决方法(0)

将字符串作为指针或文字传递时,strcmp()返回值不一致

strcmp当我注意到这一点时,我正在玩,这里是代码:

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

int main(){

    //passing strings directly
    printf("%d\n", strcmp("ahmad", "fatema"));

    //passing strings as pointers 
    char *a= "ahmad";
    char *b= "fatema";
    printf("%d\n",strcmp(a,b));

    return 0;

}
Run Code Online (Sandbox Code Playgroud)

输出是:

-1
-5
Run Code Online (Sandbox Code Playgroud)

不应该strcmp一样吗?为什么,我给我传递一个字符串作为不同的值"ahmad"或作为char* a = "ahmad".将值传递给函数时,它们是否在其堆栈中分配?

c c++ linux strcmp

32
推荐指数
2
解决办法
1852
查看次数

找到Python最长重复字符串的有效方法(From Programming Pearls)

摘自编程珍珠第15.2节

可在此处查看C代码:http://www.cs.bell-labs.com/cm/cs/pearls/longdup.c

当我使用suffix-array在Python中实现它时:

example = open("iliad10.txt").read()
def comlen(p, q):
    i = 0
    for x in zip(p, q):
        if x[0] == x[1]:
            i += 1
        else:
            break
    return i

suffix_list = []
example_len = len(example)
idx = list(range(example_len))
idx.sort(cmp = lambda a, b: cmp(example[a:], example[b:]))  #VERY VERY SLOW

max_len = -1
for i in range(example_len - 1):
    this_len = comlen(example[idx[i]:], example[idx[i+1]:])
    print this_len
    if this_len > max_len:
        max_len = this_len
        maxi = i
Run Code Online (Sandbox Code Playgroud)

我发现这idx.sort一步很慢.我认为它很慢,因为Python需要通过值而不是指针传递子串(如上面的C代码).

测试文件可以从这里 …

c python suffix-tree suffix-array programming-pearls

11
推荐指数
3
解决办法
4811
查看次数

strcmp中的奇怪返回值

在检查strcmp函数的返回值时,我在gcc中发现了一些奇怪的行为.这是我的代码:

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

char str0[] = "hello world!";
char str1[] = "Hello world!";

int main() {
    printf("%d\n", strcmp("hello world!", "Hello world!"));
    printf("%d\n", strcmp(str0, str1));
}
Run Code Online (Sandbox Code Playgroud)

当我用clang编译它时,两次调用都strcmp返回32.然而,当用gcc编译时,第一个调用返回1,第二个调用返回32.我不明白为什么第一次和第二次调用strcmp在编译时返回不同的值使用gcc.

以下是我的测试环境.

  • Ubuntu 18.04 64bit
  • gcc 7.3.0
  • 铿锵6.0.0

c gcc clang

6
推荐指数
3
解决办法
600
查看次数

Valgrind弄乱了strcmp()的返回值,为什么?

我目前正在使用valgrind-3.10.0.SVN,gcc 4.8.2和Ubuntu 14.04.这是我文件中的代码foo.c

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

int main()
{
    char foo[] = "Foo";
    char bar[] = "Bar";
    printf("%d\n", strcmp(foo, bar));
}
Run Code Online (Sandbox Code Playgroud)

我用这个命令编译:
gcc foo.c -o foo

这些是执行命令和输出:

./foo  
4

valgrind ./foo
1
Run Code Online (Sandbox Code Playgroud)

为什么Valgrind会影响我的strcmp()函数的输出?

c gcc valgrind

2
推荐指数
1
解决办法
330
查看次数