char和指针一起工作会发出警告:从不兼容的指针类型中分配

时间:2017-06-25 05:32:41

标签: c pointers

我试图理解指针以及如何将它们与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 */

1 个答案:

答案 0 :(得分:3)

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;了解你所知道的显而易见的原因。

<强> EDIT2

是不安全的
char x1[49] = "vgccgcporertfewjjqhjreuvpubfiterhmdxereotxmhcnsre";

"..."是一个空终止的字符序列(有时简称为string),表示空字符&#39; \ 0&#39;将附加到双引号内的内容。如果你在数组索引中提到了确切的字符数,或者在双引号内添加了更多的字符,那么当编译器附加&#39; \ 0&#39;时,你可以访问数组的边界之外。幸运的是,C有一个灵活的机制,你可以省略数组索引,编译器可以分配一个足够大的内存块来保存你的字符串。所以把它改成

char x1[] = "vgccgcporertfewjjqhjreuvpubfiterhmdxereotxmhcnsre";

注意感谢@ {david-bowling [ hint ]