我试图了解一些指针以及如何将它们与char类型一起使用。这里我声明一个char并给它赋值。然后我声明一个指针变量。使用'&',我相信我得到了变量的地址-我试图取消对指针的引用并设置它,这样*s1变量将打印x1中的值。我知道我可以用其他方法实现这一点,但是,我真的想知道如何将值从一个char传递到一个char指针。我收到一个不兼容的指针类型警告,我不明白为什么?

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

/* Global variable: accessible to all threads */
int total = 0;
int n1,n2;
// char *s1,*s2;
FILE *fp;

/* Prototypes */
int num_substring(void); /* Given Substrings Function */
int readf(void); /* stand in for file read */

/* Input for testing - will be from readfile */
char x1[49] = "vgccgcporertfewjjqhjreuvpubfiterhmdxereotxmhcnsre";
char x2[2] = "re";
char *s1;   /* A pointer to an char ("*s1" is a char, so s1
                       must be a pointer to an char) */
char *s2;

int main(int argc, char* argv[]) {
    readf();

    return 0;
}   /* MAIN */

// make a function to return s1, s2, n1 ,n2 maybe fp
int readf(void){
    s1 = &x1;           /* Read it, "assign the address of x1 to s1*/
    s2 = &x2;
    /* Input for testing - will be from readfile */
    n1=strlen(s1);                 /*length of s1*/
    n2=strlen(s2)-1;               /*length of s2*/
    /* ----------------------------------------- */
    return -1;
}   /* readf */

最佳答案

s1 = &x1;

不正确从
char x1[49] = "vgccgcporertfewjjqhjreuvpubfiterhmdxereotxmhcnsre";

x1是一个字符数组。所以&x1[0]是第一个字符的地址。
 s1 = &x1[0]; // should get rid of that warning

有趣的是,您可以按惯例将&x1[0]x1交换(即两者的意思相同)。因此,以下情况也应该是正确的:
 s1 = x1; // should get rid of that warning

但是,如果你能写s1 = x1;,那么你就不能写s1 = &x1;,因为你知道明显的原因。
编辑2
写东西不安全
char x1[49] = "vgccgcporertfewjjqhjreuvpubfiterhmdxereotxmhcnsre";

"..."是一个以空结尾的字符序列(有时被方便地称为string),这意味着一个空字符'\0'将被追加到双引号中。如果将数组索引中提到的确切字符数或更多字符放在双引号中,则当编译器追加“\0”时,可以访问数组边界之外的字符。幸运的是,C有一个灵活的机制,你可以省略数组索引,编译器可以完成分配内存块的任务。所以改成
char x1[] = "vgccgcporertfewjjqhjreuvpubfiterhmdxereotxmhcnsre";

感谢@david bowling的[ hint ]

关于c - char和指针一起工作会发出警告:来自不兼容指针类型的赋值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44743504/

10-11 22:12
查看更多