Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

346
Visualizações
In C, why can't an integer value be assigned to an int* the same way a string value can be assigned to a char*?

I've been looking through the site but haven't found an answer to this one yet.

It is easiest (for me at least) to explain this question with an example.

I don't understand why this is valid:

#include <stdio.h>

int main(int argc, char* argv[])
{
  char *mystr = "hello";
}

But this produces a compiler warning ("initialization makes pointer from integer without a cast"):

#include <stdio.h>

int main(int argc, char* argv[])
{
  int *myint = 5;
}

My understanding of the first program is that creates a variable called mystr of type pointer-to-char, the value of which is the address of the first char ('h') of the string literal "hello". In other words with this initialization you not only get the pointer, but also define the object ("hello" in this case) which the pointer points to.

Why, then, does int *myint = 5; seemingly not achieve something analogous to this, i.e. create a variable called myint of type pointer-to-int, the value of which is the address of the value '5'? Why doesn't this initialization both give me the pointer and also define the object which the pointer points to?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

In fact, you can do so using a compound literal, a feature added to the language by the 1999 ISO C standard.

A string literal is of type char[N], where N is the length of the string plus 1. Like any array expression, it's implicitly converted, in most but not all contexts, to a pointer to the array's first element. So this:

char *mystr = "hello";

assigns to the pointer mystr the address of the initial element of an array whose contents are "hello" (followed by a terminating '\0' null character). Incidentally, it's safer to write:

const char *mystr = "hello";

There are no such implicit conversions for integers -- but you can do this:

int *ptr = &(int){42};

(int){42} is a compound literal, which creates an anonymous int object initialized to 42; & takes the address of that object.

But be careful: The array created by a string literal always has static storage duration, but the object created by a compound literal can have either static or automatic storage duration, depending on where it appears. That means that if the value of ptr is returned from a function, the object with the value 42 will cease to exist while the pointer still points to it.

As for:

int *myint = 5;

that attempts to assign the value 5 to an object of type int*. (Strictly speaking it's an initialization rather than an assignment, but the effect is the same). Since there's no implicit conversion from int to int* (other than the special case of 0 being treated as a null pointer constant), this is invalid.

over 4 years ago · Santiago Trujillo Relatório

0

When you do char* mystr = "foo";, the compiler will create the string "foo" in a special read-only portion of your executable, and effectively rewrite the statement as char* mystr = address_of_that_string;

The same is not implemented for any other type, including integers. int* myint = 5; will set myint to point to address 5.

over 4 years ago · Santiago Trujillo Relatório

0

i'll split my answer to two parts:

1st, why char* str = "hello"; is valid:

char* str declare a space for a pointer (number that represents a memory address on the current architecture)

when you write "hello" you actually fill the stack with 6 bytes of data
(don't forget the null termination) lets say at address 0x1000 - 0x1005.

str="hello" assigns the start address of that 5 bytes (0x1000) to the *str

so what we have is :
1. str, which takes 4 bytes in memory, holds the number 0x1000 (points to the first char only!)
2. 6 bytes 'h' 'e' 'l' 'l' 'o' '\0'

2st, why int* ptr = 0x105A4DD9; isn't valid:

well, this is not entirely true!
as said before, a Pointer is a number that represent an address,
so why cant i assign that number ?

it is not common because mostly you extract addresses of data and not enter the address manually.
but you can if you need !!!...
because it isn't something that is commonly done,
the compiler want to make sure you do so in propose, and not by mistake and forces you to CAST your data as
int* ptr = (int*)0x105A4DD9;
(used mostly for Memory mapped hardware resources)

Hope this clear things out.
Cheers

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda