繁体   English   中英

C编程指针char数组

[英]C programming pointer char array

以下C程序将打印最短和最长的字符串t[0]t[n-1] 但是,当我运行此代码时,它表示存在内存问题。 我的代码出了什么问题?

问题是最后两行,带有“strcpy”。

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

void fx (char* t[], int n);

int main(void)
{
    char* t[] = {"horse", "elephant", "cat", "rabbit"};
    int n;
    n = sizeof( t )/ sizeof( t[0] );
    fx(t, n);
    printf("shortest is %s, longest is %s\n", t[0], t[n-1]);
}

void fx (char* t[], int n)
{
    char st[50], lt[50];
    strcpy(lt,t[0]);
    strcpy(st,t[0]);
    for (int i=0; i<n; i++)
    {
        if (strlen(t[i]) < strlen(st))
            strcpy(st,t[i]);
        if (strlen(t[i]) > strlen(lt))
            strcpy(lt,t[i]);
    }
    strcpy( t[0], st);
    strcpy( t[n-1], lt);
}

两个strcpy()s,

strcpy( t[0], st);
strcpy( t[n-1], lt);

错了! t[i]指向const字符串文字 - 不可修改,这会在运行时导致未定义的行为

char* t[] = {"horse", "elephant", "cat", "rabbit"};

声明一个指向字符串文字的指针数组。 字符串文字可以放在只读内存中,不能修改。 fx中的最终strcpy行正在尝试写入只读内存。

当你这样做

char *ptr = "string";

如果你这样做,那么

ptr[0]='S';

这会给你错误。 它会编译。 原因是,“字符串”被放置在内存的数据段或文本部分中并且是常量。 这使得ptr,指向常量字符串的指针,因此不允许修改。

同样在这里,所有指向字符串的指针,即horseelephant等都是常量,不应该改变。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM